CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta1 CSCI 2210: Programming in Lisp Procedures

Embed Size (px)

Text of CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta1 CSCI 2210: Programming in Lisp Procedures

  • CSCI 2210: Programming in LispProcedures

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • Example: Our-thirdFunction to get the third element of a list> (third '(a b c d e))cHow can we do this without using THIRD?Want to create our own function, OUR-THIRD that mimics THIRD> (our-third '(a b c d e))cDefinition of OUR-THIRD> (defun our-third (x) (first (rest (rest x))))OUR-THIRDMany Lisp built-in functions can be written using other Lisp built-in functionsSee Appendix B, Lisp in Lisp.

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • Example: Both-endsDefine a procedure that gives both ends of a list> (setf itinerary (Albany NYC Chicago Seattle Anchorage))> (both-ends itinerary)(ALBANY ANCHORAGE)Three stepsGet first element> (first itinerary)ALBANYGet last element> (first (last itinerary)) ANCHORAGECombine the two> (list (first itinerary) (first (last itinerary)))Define procedure> (defun both-ends (l) (list (first l) (first (last l))))

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • Example: DistanceWrite a function to find the distance between 2 points.> (defun sqr (x) (* x x))SQR> (defun distance (x1 y1 x2 y2) (sqrt (+ (sqr (- x2 x1)) (sqr (- y2 y1)))))DISTANCE> (setf originx 0 originy 0)0> (distance originx originy 2 2)1.414Must have correct number of argumentsThe value of each argument is copied to the corresponding parameteroriginxcopied tox1originycopied toy12copied to x22copied to y2

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • ScopeConsider> (setf a ORIG-A b ORIG-B c ORIG-C)ORIG-C> (list a b c)(ORIG-A ORIG-B ORIG-C)> (defun myfun (a) (setf a myfun-a) (setf b myfun-b) (list a b))> (myfun c)(MYFUN-A MYFUN-B)> (list a b c)(ORIG-A MYFUN-B ORIG-C)Value of C is copied to AParameter passing: Pass by Value (Like C/C++ default)Global variables are still accessible!Like C/C++ Global variablesLexical variable: variable declared as a parameterSpecial variable: variable not declared as a parameterA,B,CA

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • LetLet = Lisps way of defining local variables(let ( ( ) ( ) ) )Example(defun distance (x1 y1 x2 y2) (let ( (dx (- x2 x1)) (dy (- y2 y1)) ) (sqrt (+ (sqr dx) (sqr dy))) ))Let evaluates in parallel (not sequentially)Uses original values of variables in all ( ) pairs(let ( (dx (- x2 x1)) (dy (- y2 y1)) (dx_sqr (sqr dx)) (dy_sqr (sqr dy)) ) ;; Wont work! (sqrt (+ dx_sqr dy_sqr)) )

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • Let vs. Let*Let - Parallel evaluation> (setf x outside)OUTSIDE> (let ((x inside) (y x)) (list x y))(INSIDE OUTSIDE)Let* - Sequential evaluation> (setf x outside)OUTSIDE> (let* ((x inside) (y x)) (list x y))(INSIDE INSIDE)Let* Implementation of distance(let* ( (dx (- x2 x1)) (dy (- y2 y1)) (dx_sqr (sqr dx)) (dy_sqr (sqr dy)) ) ;; OK! (sqrt (+ dx_sqr dy_sqr)) )

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • Exercise1. Rewrite the distance function to use setf instead of let. Explain the difference.2. Write the function solve-quadratic such that, given a,b,c, the function finds all values of x for which ax^2 + bx + c = 0.x1 = (-b + sqrt (b^2 - 4ac)) / 2ax2 = (-b - sqrt (b^2 - 4ac)) / 2aThe function should return both values of x as a list of two elements. For example,> (solve-quadratic 1 -2 1)(1.0 1.0)

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • Example: Solve-quadraticSolution to solve-quadratic(defun solve-quadratic (a b c) (let ((sqrt_clause (- (* b b) (* 4 a c))) (neg_b (- b)) (two_a (* 2 a)) ) (list (/ (+ neg_b (sqrt sqrt_clause)) two_a) (/ (- neg_b (sqrt sqrt_clause)) two_a))))Notes - No error checking is done(- (* b b) (* 4 a c)) might result in a negative numberWhat happens when you try to take sqrt of a negative number?What happens when the value of A is zero?NeedPredicates - to determine when error conditions occur (e.g. =)Conditionals - to do something else when error occurs

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • EQUAL does not = EQLSeveral predicates check equalitySlightly different semanticsCan be confusingEquality predicatesEqual - Are two argument values the same expression?Eql - Are two argument values the same symbol or number?Eq - Are two argument values the same symbol?= - Are two argument values the same number?General Rule of ThumbUse = when you want to compare numbersUse EQUAL otherwise

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • Relationships Bet Equality PredsEQ vs. == returns T if two numbers are the same, regardless of their typeEQ returns T if two arguments are the same symbolSame chunk of memoryIdentical primitives sometimes are EQ Examples> (eq 4 4);; EQ:T=:T(C)> (eq (/ 1 4) 0.25);; EQ:NIL=:T(A)> (eq A A);; EQ:T=:Error(D)> (eq 4.0 4.0);; EQ:NIL=:T(A)=EQEQLEQUALABCDFE

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • EQL vs. =EQLArguments are EQL if they are either EQ or they are equivalent numbers of the same typeExamples> (eq 4.0 4.0) ;; EQ:NIL EQL:T =:T (B)> (eq 4 4.0);; EQ:NIL EQL:NIL =:T (A)EQUALArguments are EQUAL if they are either EQL or they are Lists whose elements are EQUALPerforms an element by element comparison of lists

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • EQUAL vs. EQL vs. =EQUAL vs. EQL> (setf X (A (B (C))))> (setf Y X)> (setf Z (A (B (C))))X and Y are EQUAL and EQLX and Z are EQUAL but not EQLThey dont point to the SAME memoryBut, if you do an element by element comparison of the lists, they are equalEQUAL vs. => (EQUAL 4 4.0)NIL> (= 4 4.0)TBCAZBCAXY

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • Data Type PredicatesData Type PredicatesCompare objects to determine their typeatom - Is argument an atom?numberp - Is argument a number?symbolp - Is argument a symbol (a non-numeric atom)?listp - Is argument a list?Examples> (list pi ABC)(3.14159 ABC)> (list (atom pi) (atom ABC))(T T)> (list (numberp pi) (numberp ABC))(T NIL)> (list (symbolp pi) (symbolp ABC))(NIL T)> (list (listp pi) (listp ABC) (listp (A B))(NIL NIL T)

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • Number PredicatesNumber predicatesnumberp - Is it a number?zerop - Is it zero? Argument must be a numberplusp - Is it positive? Argument must be a numberminusp - Is it negative? Argument must be a numberevenp - Is it even?oddp - Is it odd?> - Is the list of arguments in descending order? (e.g. (> 5 4))< - Is the list of arguments in ascending order?

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • If, When, UnlessIf(if )if is true is evaluated, otherwise is evaluated.When(when )If is true, then other arguments are evaluated. Unless(unless )If is false, then other arguments are evaluated.

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • CondCond format(COND ( ) ( ) ( ) ( ) ( )Semantics1. Evaluate , , until you get to a such that evaluates to a nonNIL value2. Evaluate 3. Return value of the last clause executedIf all tests evaluate to NIL, result of COND is NIL

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • ExampleDefine a function to find area(defun area (type r) (cond ((equal type circle) (* PI R R)) ((equal type sphere) (* 4 PI R R)) ((equal type square) (* R R) ((equal type cube) (* 6 R R)) ( t (print Error) ))Define a function, compute-grade, to determine the letter grade.(compute-grade 81.5)B

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • CaseSimilar to COND, but is more elegant when checking for equality(defun area (type r) (case type (circle (* PI R R)) (sphere (* 4 PI R R)) (square (* R R) (cube (* 6 R R)) (otherwise (print Error) ))Format(case ( ) ( ) ( ) (otherwise )

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • Case (2)Notes is evaluatedBut, , are NOT evaluatedOTHERWISE or T always evaluate to nonNILIf no matches are found, the CASE statement returns NILA form may contain a list. In this case, the can match ANY element of the list(defun circularp (type) (case type ((circle sphere) T) (otherwise NIL)))(circularp cube)Technical note: the MEMBER function is used to do the comparison.

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • Both-ends RevisitedBoth-ends with error handling(defun both-ends (l) (if (listp l) (case (length l) (0 NIL) (1 (list (first l) (first l))) (t (list (first l) (first (last l))))) NIL))

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • Solve-quadratic revisitedSolve-quadratic with error checkingChecks for errors; returns NIL instead(defun solve-quadratic (a b c) (if (not (and (numberp a) (numberp b) (numberp c))) NIL ; at least one argument is not a number (let ((sqrt_clause (- (* b b) (* 4 a c))) (neg_b (- b)) (two_a (* 2 a)) ) (cond ((minusp sqrt_clause) NIL) ((= 0 a) NIL) ; Could have used zerop (t (list (/ (+ neg_b (sqrt sqrt_clause)) two_a) (/ (- neg_b (sqrt sqrt_clause)) two_a)))))))What happens if we don't include the clause(minusp sqrt_clause) By default, Lisp arithmetic operations handle complex numbers

    CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta

  • FactorialDefinition of FactorialC++ Implementationint factorial (int x) { int i,f;