CSCI 2210: Programming in Lisp - Computer CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta 1

Embed Size (px)

Text of CSCI 2210: Programming in Lisp - Computer CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta 1

  • CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta 1

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 1

    CSCI 2210: Programming in Lisp

    ANSI Common Lisp, Chapters 5-10

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 2

    Progn

    • Progn • Creates a block of code • Expressions in body are evaluated • Value of last is returned

    (if ( < x 0) ( progn (forma t t "X is l ess than z ero ") (forma t t "and m ore than on e statemen t ") (forma t t "needs to be exec uted in th e IF") (- x) ) )

    • Prog1 • Same as progn, except value of f irst expression is returned

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 3

    Block

    • Like a progn with • A name • An "emergency exit"

    –return-from - Returns from a named block –return - Returns from a block named NIL

    • Examples > (bl ock head ( f ormat t " Here we go " ) ( r eturn-fro m head 'id ea) ( f ormat t " We'll neve r see this" ) )

    Here we go. IDEA

    > (bl ock nil (r eturn 27)) 27

  • CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta 2

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 4

    Implicit use of Blocks

    • Some Lisp constructs implicitly use blocks • All i teration constructs use a block named NIL (note return)

    > ( dol ist (x '( a b c d e) ) ( f ormat t " ~A " x) ( i f ( eql x ' c) (retur n 'done)))

    A B C DONE

    • Defun uses a block with same name as the function > ( def un foo () ( r eturn-fro m foo 27))

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 5

    Iteration

    • DOTIMES (Review) ( doti mes ( ) )

    –Example ( doti mes (i 5) ( print i)) ;; prints 0 1 2 3 4

    • DOLIST ( doli s t ( ) )

    –Example ( doli s t ( elem ' ( a b c d)) (print ele m)) ;; pri nts a b c d

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 6

    Example of DOLIST

    • Given a list of ages of people, how many adults? –List of ages

    > ( se t f ages '( 3 4 17 21 22 34 2 7))

    –Adult defined as: >= 21 years old > ( def un adultp (age) (>= age 21))

    –Using Count-if ( defu n count-ad ult (ages) (count-if # 'adultp ages))

    –Using dolist ( defu n count-ad ult (ages &aux ( nadul t 0)) ( dolist (age ages nadu l t ) (if ( adul t p age) ( setf nadult ( + 1 nadul t )))))

  • CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta 3

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 7

    Example (cont.)

    • Get the ages of the first two adults ( defu n first-tw o-adults ( ages & aux ( nadult 0) ( adults ni l )) ( dolist (age ages) (if ( adul t p age) ( progn ( setf nad ult (+ nadu l t 1)) (push age adults) (if (= nadult 2) (re t urn adult s ))))))

    • Notes • PROGN (and PROG1) are like C/C++ Blocks { … }

    > (pr og1 ( setf a 'x) ( set f b 'y) ( se t f c 'z)) X

    > ( pr ogn ( setf a 'x) ( set f b 'y) ( se t f c 'z)) Z

    • RETURN exits the DOLIST block –Note: does not necessarily return from the procedure! –Takes an optional return value

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 8

    DO

    • DO is more general than DOLIST or DOTIMES • Example

    ( defu n do- expt ( m n) ;; Return M^N (d o ((result 1) ;; Bind variab l e ‘Result ’ to 1 (expone nt n)) ;; Bind variab l e ‘Expone nt’ to N (( zerop exponent) r esult) ;; t est and r eturn valu e ( setf re s ult (* m r esult)) ;; Body ( setf ex ponent (- exponent 1) ) ;; Body

    • Equivalent C/C++ definition int do_expt ( in t m, int n) { in t result, exponent; fo r (result= 1,exponent =n; (expone nt != 0); ) { result = m * result ; exponent = exponent - 1; } re t urn resul t ; }

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 9

    DO Template

    • Full DO Template (There is also a DO*) (DO ( ( ) ( ) … (< pN> < iN > ) ) ( … < aN> ) < body> )

    • Rough equivalent in C/C++ for ( = , =,…,< pN>=; //Note : Lisp=par allel !(); // C/C++ has a “continua t ion-test” = , =,…,< pN>=) { } ; ; … ; < aN>; ; // No t e: (DO…) i n Lisp eva l uates to // No t e: ,< p2>,…,< pN> are now re s tored to original v alues

  • CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta 4

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 10

    Do-expt, Loop

    • Here is another (equivalent) definition of do-expt ( defu n do- expt ( m n) (d o ((result 1 (* m re s ult)) (expone nt n (- ex ponent 1))) (( zerop exponent) r esult) ;; Note t hat there is no body ! ) )

    • Loop • An infinite loop, terminated only by a (return)

    (loop (pr i nt '(Say uncle)) (if (equal (r ead) 'uncl e) (return) ) )

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 11

    Multiple Values

    • We said each lisp expression returns a value • Actually, can return zero or more values (i.e. multiple values)

    > (ro und 7.6) ; Round ret urns two va l ues 8 -0.4

    > ( se t f a (roun d 7.6)) 8 ; Setf expects only one value, so it takes the first (8)

    > a 8

    • How can you get all values? > (mu l tiple-val ue-list (r ound 7.6))

    (8 -0.4) > (mu l tiple-val ue- setq ( i ntpart dif ) (round 7. 6))

    8 > int part

    8 > dif

    -0.4

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 12

    Generating Multiple Values

    • How? Use val ues > (va l ues 1 2 3 ) ; Genera t es 3 retur n values

    1 2 3

    > ( def un uncons ( aList ) ( v alues (fir s t aList ) ( rest aLis t ))) UNCONS

    > ( unc ons '(A B C)) A (B C)

    > (fo r mat t "He l lo World" ) " Hello World" NIL

    > ( def un format - without-r eturn (out s tr &rest args ) ( apply #'fo r mat out s t r args ) ( v alues)) ; A funct i on with no return va l ue!

    FORMAT-WITHOUT-RETURN > (fo r mat-witho ut-return t "Hello")

    Hello >

  • CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta 5

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 13

    Functions about functions

    • FBOUNDP - Is a symbol the name of a function? > ( fb oundp '+)

    T

    • SYMBOL-FUNCTION - returns function > (sy mbol-funct i on '+)

    # > ( se t f (symbol - function ' sqr ) #'(la mbda (x) ( * x x)))

    # > ( def un sqr (x ) (* x x)) ; this is equivalent to above

    SQR

    • Defun and symbol-function define global functions • Local functions can be defined using LABELS

    > ( def un add3 ( x ) ( l abels ((a dd1 (x) (+ x 1)) (a dd2 (x) (+ x 2))) (add1 (ad d2 x))))

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 14

    Closures

    • Want a function that can save some values for future access/update • Can use global variables for this

    > ( se t f *number - of-hits* 0) ; Global variable

    0 > ( def un increm ent-hits ( ) ( incf *nu mber-of-hi t s*))

    INCREMENT-HITS > (in c rement-hi t s)

    1 > (in c rement-hi t s)

    2

    • But, what if someone clobbers the variable? > ( se t f *number - of-hits* " This varia ble is now a string" )

    " This variable is now a string" > (in c rement-hi t s)

    Error: '*number-of-hits* ' is not of the expected type: NUMBER

    • Want something like "static" variables in C/C++.

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 15

    Closures (continued)

    • One use of closures is to implement 'static' variables safely • Closure -- Combination of a function and environment

    –Environment can include values of variables > (le t ((number - of-hits 0 ) ) ( defun incr ement-hits () ( incf n umber-of-h i ts)))

    INCREMENT-HITS –number - of-hits is a free variable – It is a lexical variable (has scope) –A function that refers to a free lexical variable is called a closure

    • Multiple functions can share the same environment > (le t ((number - of-hits 0 ) ) ( defun incr ement-hits ( ) ( incf number-of-hi t s)) ( defun rese t -hit-coun t er() ( setf number-of - hits 0))

  • CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta 6

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 16

    Closures (cont)

    • Example 1 > ( def un make-a dder (n) ; returns fu nction to add n to x # ' (lambda ( x ) (+ x n) ) ) > ( se t f add3 (m ake-adder 3)) ; retur ns functio n to add 3

    # > ( fu ncall add3 2) ; Call function a dd3 with a r gument 2

    5 > ( se t f (symbol - function ' add3-b) (m ake-adder 3)) > (ad d3-b 5)

    8

    • Example 2 - Returns an "opposite" function > ( def un our-co mplement ( f ) # ( lambda (& r est args ) (not (ap ply f args ) ))) > ( mapcar (our- c omplement # 'oddp ) '( 1 2 3 4))

    (NIL T NIL T)

    • Tip of the iceberg in terms of possibilities

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 17

    Trace

    • Format (trac e )

    • Example > ( def un factor