CSC 330 Lecture Notes Week 10
Motivations for Functional Programming in Lisp
>(setq z 0) 0 >(defun expr (x) (setq z (+ z x))) expr >(defun f (x y) (+ x y z)) f >(f (expr 1) (expr 1)) 5 >(f (expr 1) (expr 1)) 11
>(setq x '((a 10) (b 20) (c 30)))
((A 10) (B 20) (C 30))
>(load "setfield.l")
Loading setfield.l
Finished loading setfield.l
T
>(setq y (assoc 'b x))
(B 20)
>y
(B 20)
>(dsetfield 'b "abc" x)
("abc")
>x
((A 10) (B "abc") (C 30))
>y
(B "abc")
>(defun f (x y z) ... ) >(f (big1 ...) (big2 ...) (big3 ...))
Figure 1: Two models of expression evaluation.
>(defun f (x y)
(cond ( (= x 1) x )
( t y )
)
)
>(f 1 (some-hugely-lengthy-computation))
>(defun g (x y)
(cond ( (= x 1) z ) ;NOTE: z is free
( t y )
)
)
>(g 1 (setq z 1))
L>(defun (lazy+ (x y) (+ x y))) lazy+ L>(lazy+ 2 (lazy+ 2 (lazy+ 2 2))) 8
>(defun not-so-stupid-but-lazy (x y)
(cond ( (= 1 1) x )
( t y )
)
)
>(defun infinite-computation ()
(prog ()
loop (go loop)
)
)
>(not-so-stupid-but-lazy 1 (infinite-computation))
1
>(defun all-ints () (cons 0 (1+ (all-ints)))) all-ints >(nth 2 (all-ints)) 2