Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CSE240 Lecture 22

CSE240 Lecture 22

Introduction to Programming Languages
Control Structures in LISP
(202011)

B546a9b97d993392e4b22b74b99b91fe?s=128

Javier Gonzalez

January 22, 2017
Tweet

Transcript

  1. jgs CSE 240 Introduction to Programming Languages Lecture 22: Control

    Structures in LISP Javier Gonzalez-Sanchez javiergs@asu.edu PERALTA 230U Office Hours: By appointment
  2. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 2 jgs

    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.
  3. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 3 jgs

    Control Structures § (if (<= 3 2) (* 3 9) (+ 4 2 3)) ; if (3<=2) {return 3*9;} else {return 4+2+3;} 9 § (if (> 2 3) 9) ; if (2>3) {return 9;} else {return nil} NIL § (if (= 2 2) (if (> 3 2) 4 6) 9) 4 § (+ 4 (if (= 2 2) (* 9 2) 7) ) 22
  4. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 4 jgs

    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
  5. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 5 jgs

    Loop (dotimes) dotimes is an iterator with this format (dotimes (var high-val optional-return-val) expr1 expr2 …) • (dotimes (x 4) (print "hello")) "hello" "hello" "hello" "hello" NIL • (setf bag 2) 2 • (dotimes (x 3) (setf bag (* bag bag))) NIL • (print bag) 256
  6. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 6 jgs

    Global Variables § Variables are set with the macro setf. • (setf x (* 3 2)) 6 • x 6 • (setf y (+ x 3)) 9
  7. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 7 jgs

    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
  8. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 8 jgs

    Nested Variable Scope § (let ((x 3) (y (+ 4 9))) (* x y)) 39 § (let ((x 3)) (print x) (let (x) (print x) (let ((x "hello")) (print x)) (print x)) (print x) (print ”end")) 3 NIL "hello" NIL 3 "end" "end"
  9. jgs CSE 240 Introduction to Programming Languages Javier Gonzalez-Sanchez javiergs@asu.edu

    Spring 2018 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.