with LISP| Control Structures, Function-Making, and Data Structures Javier Gonzalez-Sanchez [email protected] javiergs.engineering.asu.edu Office Hours: By appointment
2 Control Structures • There are some evaluable lists which are not functions. • These lists are known as macros or special forms. • The control structure if is a special form.
4 Control Structures • if only allows one test-expression, one then-expression, and one optional-else-expression. • To do more things in the then-expression we need to make a block. Blocks are made with the special form progn, which takes the form: (progn expr1 expr2 expr3 ...) • (if (> 3 2) (progn (print "hello") (print "yo") (print "whassup?") (+ 2 2)) (+ 1 2 3)) "hello" "yo" "whatsup?" 4
7 Local Variables • let declares local variables with each declaration. Then it evaluates the expressions in order (as a block). • let returns the value of the last expression. • (setf x 4) (let ((x 3)) ; x declared local (print x) (setf x 9) ; change the value of x (print x) (+ x x) ;this is the returned value ) 3 9 18 • x ;outside the let, we're back to global again 4
9 Function Making • functions are created by calling a function-making macro. This macro is called defun. • the function returns the value of the last expression. (defun function-name-symbol (param1 param2 param3 ...) expr1 expr2 expr3 ... )
13 Data Structures • first returns the first item in a list. The old name of first is car (content of the address). • rest returns a list consisting of everything but the first item. It does not damage the original list. The old name of rest is cdr (content of the decrement register). • append hooks multiple lists together. • cons takes an item and a list, and returns a new list consisting of the old list with the item tacked on the front.
14 Data Structures • ( setf myList '( (A B) C (D) ) ) ((A B) C (D)) • (car (car myList) ) ;( first ( first ) ) A • (cdr( car myList)) ;( last ( first ) ) (B) • (car (cdr myList)) ;( first ( last ) ) C
15 Data Structures • ( setf myList2 '(A (B () (C () () )) (D (E () () ) () ) ) ) (A (B NIL (C NIL NIL)) (D (E NIL NIL) NIL)) • (car (car myList2)) ;( first ( first (L)) Error: Cannot take CAR of A. • (cdr( car myList2)) ;( last ( first (L)) Error: Cannot take CDR of A. • (car (cdr myList2)) ;( first ( last (L)) (B NIL (C NIL NIL))
16 Loop (dolist) • (dolist (x '(a b c d e)) (print x)) A B C D E NIL dolist is an iterator with this format (dolist (var list-to-iterate-over optional-return-val) expr1 expr2 …)
17 Loop (dolist) • (defun my-reverse (list) (let (new-list) ; empty list (dolist (x list) (setf new-list (cons x new-list)) ) new-list) ) MY-REVERSE • (my-reverse '(a b c d e f g)) (G F E D C B A)
Fall 2017 Disclaimer. These slides can only be used as study material for the class CSE240 at ASU. They cannot be distributed or used for another purpose.