100 likes | 219 Views
Functional Programming. 04 Control. Control-Blocks. Common Lisp has 3 basic operators for creating blocks of code progn block tagbody If ordinary function calls are the leaves of a Lisp program, these operators are used to build the branches. Control-Blocks.
E N D
Functional Programming 04 Control
Control-Blocks • Common Lisp has 3 basic operators for creating blocks of code • progn • block • tagbody • If ordinary function calls are the leaves of a Lisp program, these operators are used to build the branches
Control-Blocks • > (progn (format t “a”) (format t “b”)(+ 11 12))ab23 -> only the value of the last expression is returned
Control-Blocks • > (block head (format t “Here we go.”) (return-from head ‘idea) (format t “We’ll never see this.”))Here we go.IDEA • Calling return-from allows your code to make a sudden but graceful exit from anywhere in a body of code • Expressions after the return-from are not evaluated
Control-Blocks • > (block nil (return 27))27 • > (dolist (x ‘(a b c d e)) (format t “~A “ x) (if (eql x ‘c) (return ‘done)))A B CDONE
Control-Blocks • The body of a function defined with defun is implicitly enclosed in a block with the same name as the function • (defunfoo()(return-fromfoo27)) • (defunread-integer(str)(let((accum0))(dotimes(pos(lengthstr))(let((i(digit-char-p(charstrpos))))(ifi(setfaccum(+(* accum 10) i)) (return-from read-integer nil)))) accum))
Control-Blocks • Within tagbody, you can use go • > (tagbody (setf x 0)top (setf x (+ x 1)) (format t “~A “ x) (if (< x 10) (gotop)))1 2 3 4 5 6 7 8 9 10 • This operator is mainly something that other operators are built upon, not something you would use yourself Ugly code!!
Control-Blocks • How to decide which block construct to use? • Nearly all the time you’ll use progn • If you want to allow for sudden exits, use block • Most programmers will never use tagbody explicitly
Control-Context • let • Takes a body of code • Allows us to establish variables for use within the body • > (let ((x 7) (y 2)) (format t “Number”) (+ x y))Number9
Control-Context • One let-created variable can’t depend on other variables created by the same let • (let ((x 2) (y (+ x 1))) (+ x y)) • ((lambda (x y) (+ x y)) 2 (+ x 1)) • > (let* ((x 1) (y (+ x 1))) (+ x y))3 equivalent