Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 LISP (Lecture Note #7) 인공지능 이복주 단국대학교 컴퓨터공학과. 2 Slide made by Bogju Lee Outline  What is LISP  Variables and Functions  Data Types  SETF  Math.

Similar presentations


Presentation on theme: "1 LISP (Lecture Note #7) 인공지능 이복주 단국대학교 컴퓨터공학과. 2 Slide made by Bogju Lee Outline  What is LISP  Variables and Functions  Data Types  SETF  Math."— Presentation transcript:

1 1 LISP (Lecture Note #7) 인공지능 이복주 단국대학교 컴퓨터공학과

2 2 Slide made by Bogju Lee Outline  What is LISP  Variables and Functions  Data Types  SETF  Math Operations  S-expressions  CONS Cell  …

3 What is LISP?  A LISt Processing language –The basic data structure is linked list  A functional programming language –Each expression in LISP is a function that returns a value  An interpretive language –Prompt at which you type commands. –Type-eval-print loop –Two things to type: variables or functions –Running LISP programs involves interacting with the LISP interpreter –LISP programs can also be compiled

4 Why LISP? Why LISP for AI programming?  LISP supports symbol manipulation better –Symbols are the basic entity of the language  The interpretive nature makes it easy to “try a new idea’’ and prototype  Functions are in the form of linked lists –Easier to write learning programs  Historical Reason –Most AI programs in the U.S. have been developed in LISP –However, most AI programs in Europe have been developed in PROLOG

5 Variables and Functions  Variables –Non-case sensitive –No length limit –When typed at prompt, print the value “bounded”.  Functions –Form of a list of things enclosed in parentheses. –(Name_of_the_function argument1 argument2 …) –Evaluation order: argument1, argument2,.. and then call the function.

6 Data Types  Integers, floating-point numbers, strings, and characters  Symbols –Kind of strings, but not surrounded by double-quote. –Stored in efficient internal data structures (hash tables) so –LISP can quickly determine when two symbols are identical.  Variable vs. Symbol –To differentiate, use a single-quote for symbol. –> A –23 –> ‘A –A

7 Special Symbols  NIL represents an empty list.  NIL is a terminator of a list.  A list is usually built by inserting its elements into NIL in the reverse order.  NIL can also represent “false”.  The special symbol representing “true” is T.

8 SETF  (SETF –Evaluate the expression and set the value to the variable  Example –> (setf a 3) ; comment start with ‘;’ –3 –> (setf b “foo”) ; a string –“foo” –> (setf c ‘bar); a symbol –BAR; converted to upper case –> (setf d b) –“foo”

9 Math Operations  +, -, *, /  FLOAT, ROUND, SQRT, EXPT, LOG, EXP

10 S-expressions  A list is an S-expression.  Nested list is also an S-expression.  (1 2 (3 4) 5))

11 CONS Cell  CONS cell: dynamically-allocated piece of memory in the LISP image  Automatic garbage collection  A CONS cell contains two pointer: CAR and CDR.  The CAR pointer usually points to a value (e.g., a symbol, or a number).  The CDR pointer usually points to the next CONS cell in a linked list. CAR CDR

12 List  A linked list always terminates by having the CDR of the last CONS cell pointing to a special symbol: NIL.  Example: (John loves Mary) JohnlovesMary NIL

13 CONS  The function CONS returns a newly created CONS cell. –The function takes two arguments. –The CAR part of the new cell points to the first argument. –The CDR part of the new cell points to the second argument.  Example: (CONS ‘Mary NIL) returns –(MARY) Mary NIL

14 CONS (2)  Using CONS to insert an item to the front of a list  (CONS )  Example: (CONS 'John (CONS 'loves (CONS 'Mary NIL)))  returns  First CONS call returns (MARY)  Second CONS call returns (LOVES MARY)  Third CONS call returns (JOHN LOVES MARY)

15 Nested Sublists  A sublist is a list pointed by a CAR pointer of a CONS cell  Example: ( John loves ( play tennis ) ) Johnloves NIL play tennis

16 CONS (3)  Using CONS to insert sublists  When CONS insert a list into another list. The former becomes a sublist of the latter.  Example:  > (CONS '(Amazon BN) '(sells books on Internet))  ((AMAZON BN) SELLS BOOKS ON INTERNET)

17 CAR, CDR  List access  (CAR ) returns the first element of the list.  (CDR ) returns the remaining list (i.e., everything except the first element).  Example: (CAR '(John loves Michelle)) returns  JOHN  Example: (CDR '(John loves Michelle) ) returns  (LOVES MICHELLE)

18 LIST  Other list creating functions  (LIST... ) returns a list  whose first element is, second element is ,...., Nth element is.  Example: –> (LIST 'John 'loves ’Michelle) –(JOHN LOVES MICHELLE) –> (LIST 'John 'loves (LIST `AI `research)) –(JOHN LOVES (AI RESEARCH)) –> (SETF A 3) –> (LIST A (LIST 1 2) ‘foo) –(3 (1 2) FOO)

19 APPEND  Concatenating lists  (APPEND ) returns a list that is the result of concatenating and.  > (APPEND '(Orange Apple) '(Grape))  (ORANGE APPLE GRAPE)  APPEND can also be used to concatenate more than two lists.  > (APPEND '(play) '(tennis) '(football baseball) ) ) )  (PLAY TENNIS FOOTBALL BASEBALL)

20 Other List Functions  LENGTH –> (length ‘(1 2 (3 4) 5)) –4  FIRST –> (first ‘(a b c)) –A  SECOND –> (second ‘(a b c)) –B  REST –> (rest ‘(a b c)) –‘(B C)  NTH –> (nth 2 ‘(a b c)) –C  REVERSE –> (reverse ‘(a b c)) –(C B A)

21 Evaluation  LISP executes/interprets an expression through an evaluation procedure.  Example:  (+ 3 5) evaluates to ==> 8  (CONS ‘A NIL) evaluates to ==> (A)  3 evaluates to ==> 3  ‘A evaluates to==> A  (> 5 3) evaluates to==> T

22 Evaluation Rules  A number evaluates to itself  A symbol evaluates to its value. –SETQ assigns a value to a symbol  A list is evaluated by –treating the first element as a function –evaluating each arguments of the function in a left- to-right order  An expression preceeded by a quote symbol ‘ evaluates to the expression itself.

23 Quote  Quote symbol ‘ is a short hand for a function QUOTE  (QUOTE )  QUOTE is a special function that prevents LISP from evaluating its argument.  QUOTE returns the argument literately.  Example: (quote (dummy-fn 2))  ==> (DUMMY-FN 2)

24 SETQ  Assignment and binding  A symbol (variable) can be assigned a value (called its binding) using SETQ.  (SETQ )  Example: (SETQ A ‘(A B C)) ==> (A B C) A evaluates to ==> (A B C)  Evaluating a symbol that does not have a value assigned (i.e., no binding) causes error  Ex: B evaluates to ==> Error: Unbound Variable

25 Change Binding  All other functions do NOT change the bindings  In particular, CAR and CDR are non- destructive.  > (setq my-friends ‘(Superman Batman Robin) )  (Superman Batman Robin)  > (car (cdr my-friends))  Batman  > my-friends  (Superman Batman Robin)

26 Change Binding (2)  CONS does not change bindings either.  > (CONS ‘J-Bond my-friends)  (J-Bond Superman Batman Robin)  > my-friends  (Superman Batman Robin)  > (setq my-friends (CONS ‘J-Bond my- friends) )  (J-Bond Superman Batman Robin)  > my-friends  (J-Bond Superman Batman Robin)

27 DEFUN  A function is defined using DEFUN  (DEFUN (... )... )  All arguments are passed by value.  The body of the function may contain any number of expressions (i.e., function calls)  The function returns the value returned by the last expression.

28 DEFUN (2)  >(defun range (n)  (cond ((not (numberp n)) 'not-number)  ((< n 0) 'negative)  ((> n 0) 'positive)  (T 'zero)))   > (range 52.03)  POSITIVE

29 DEFUN (3)  (defun square (x)  (times x x))  (defun add-friend (new-friend friends)  (cons new-friend friends) )  > (square 5)  25  > (add-friend ‘B-Gates my-friends)  (B-Gates J-Bond Superman Batman Robin)

30 Symbol and Function with the Same Name  Changing a symbol’s binding does not change its function definition  >(setq cons ‘list)  LIST  >(setq b (cons cons nil))  (LIST)  > cons  LIST  > (cons ‘cons b)  (CONS LIST)

31 Predicates  Functions that return ``true’’ (i.e., T) or ``false’’ (i.e., NIL).  type-testing predicates  (NULL ) returns T if is NIL (empty list), otherwise NIL.  (LISTP ) returns T if is a list, otherwise NIL.  (ATOM ) returns T if is an atom (i.e., a symbol, a number, or NIL).  (NUMBERP ) returns T if is a number

32 EQ, EQUAL  Equality-testing Predicates: EQ, =, STRING=, EQUAL  (EQ ) returns T if two arguments are two identical atoms (symbols and characters). –> (EQ ‘(Banana Apple) ‘(Banana Apple)) –NIL  (= ) –> (= 5 (/ 10 2)) –T  (STRING= )  (EQUAL ) returns T if two arguments are identical atoms or identical lists (S-expressions). –> (EQUAL ‘(Banana Apple) ‘(Banana Apple)) –T –> (EQUAL (LIST ‘a ‘b) (list ‘b ‘a)) –NIL

33 MEMBER  (MEMBER ) returns T if is an atom that is a top-level element of.  > (setq my-friends ‘(MacGyver (Batman Robin)) )  > (member ‘MacGyver my-friends)  T  > (member ‘Batman my-friends)  NIL  > (member ‘(Batman Robin) my-friends)  NIL

34 34 Slide made by Bogju Lee Summary  What is LISP  Variables and Functions  Data Types  SETF  Math Operations  S-expressions  CONS Cell  …

35 35 Slide made by Bogju Lee Outline  IF, PROGN  COND  AND, OR, NOT  Recursive Functions  LET  FORMAT  EVAL  APPLY  FUNCALL  MAPCAR  REMOVE

36 IF, PROGN  Conditional Expression: IF, PROGN  (IF [ ]) –Takes the first expression if the condition is non-nil (true) –Optional second expression is taken if the condition is nil (false). –> (if (< 2 3) ‘A (+ 2 3)) –A  (PROGN..) –Combine multiple forms to evaluate as a single consequence  > (if (= a b) ; suppose A=5 and B=5  (progn  (format t "A equals B.~%") ; ~% means new line.  a) ; trivial case  (/ (+ a b) 2)) ; print the average  A equals B.  5

37 COND  COND is an N-branch conditional expression  (COND (... )  (... ) ...  (... ) )  Each test is evaluated sequentially until a test returns true.  Expressions following that test will be executed.  COND returns the value returned by the last expression associated with the test

38 COND - Example  (defun select-character (enemy)  (cond ( (eq enemy ‘Penguin)  ‘Batman)  ( (eq enemy ‘Catwoman)  ‘J-Bond )  ( (eq enemy ‘Black-Knight)  ‘(White-Knight King-Arthur) )  )

39 COND with T Condition  > (setf a –3)  > (cond ((< a 0) ‘negative)  ((> a 0) ‘positive)  (T ‘zero))  NEGATIVE  (defun select-character (enemy)  (cond ( (eq enemy ‘Penguin)  ‘Batman)  ( (eq enemy ‘Catwoman)  ‘J-Bond )  ( (eq enemy ‘Black-Knight)  ‘(White-Knight King-Arthur ) )  ( T ; for all other enemies  ‘SuperMan) ; ask Superman for help  )

40 AND, OR, NOT  Binding more complex conditions  Simple tests can be combined into a complex one using AND, OR, NOT.  (AND... ) evaluates tests in a left-to-right order.  It returns NIL when it encounters the first test that evaluates to NIL (remaining tests are not evaluated).  If all the tests return non-NIL, AND returns the value of the last test (i.e., testn).  (Defun safe-caar ( L )  (and (listp L)  (listp (car L))  (car (car L))  ) )

41 AND  > (safe-caar ‘A)  NIL  > (safe-caar ‘( ( A ) ) )  A  > (caar ‘A)  Error!

42 OR and NOT  (OR... ) evaluates tests in a left-to-right order. –It returns T when it encounters the first test that evaluates to T (remaining tests are not evaluated). If all the tests return NIL, OR returns NIL.  (NOT ) returns T if is NIL, returns NIL if is non-NIL. –> (NOT (NULL ‘(A B C) ) ) –T

43 Using AND, OR in COND  (defun Evaluate-feeling ( sentence )  (cond ( (OR (member ‘hate sentence)  (member ‘dislike sentence))  ‘hatred)  ( (AND (member ‘I sentence)  (member ‘feel sentence) )  ‘self-centered )  ( T  ‘happy)  ) ; end of cond  ) ; end of defun

44 Martin and the Dragon  Martin: Are there enemies in the list of attendees of King Arthur’s party tonight?  (Micky SnowWhite Bishop BlackKnight WhiteKnight RoboCop SirLancelot Modred Magician)  Dragon: I will only tell you whether the first one in the list is an enemy or not.  What should Martin do?

45 Recursive Functions  Functions that call themselves  A LISP version of Martin’s solution  (defun find-enemy ( guest-list )  (cond ( (member (car guest-list) enemies)  T ) ; Yes, there is an enemy  ( T  (find-enemy (cdr guest-list) ) )  ) ; end of cond  ) ; end of defun

46 Factorial Example  N! = N*(N-1)!   >(defun fact (n) (* n (fact (- n 1))))  FACT  This is actually incomplete!  Consider the termination condition.  >(defun fact (n)  (if (= n 1) 1 (* n (fact (- n 1)))))  FACT   >(fact 5)  120

47 Member Example  Recursion is especially useful for list processing.  Many problems can be thought of recursively as applying to either the first element of a list or the rest.  Determine whether some symbol occurs in a list.  >(defun our-member (sym lst)  (cond ((null lst) nil) ; return false if empty list  ((eq sym (first lst)) T) ; we can stop here  (T (our-member sym (rest lst))))) ; ow, recursion  OUR-MEMBER  >(our-member 'b '(a b c))  T

48 Fixing the Infinite Recursion  (defun find-enemy ( guest-list )  (cond ( (null guest-list)  NIL ) ; No, there are no enemies.  ( (member (car guest-list) enemies)  T ) ; Yes, there is an enemy  ( T  (find-enemy (cdr guest-list) ) )  ) ; end of cond  ) ; end of defun

49 Martin and the Dragon  Martin: Can you tell me the names of those enemies that are in the attendee list?  Dragon: (yawn) I will only tell you whether the first attendee in the list is an enemy or not.

50 Building Lists Using Recursion  (defun identify-enemy ( guest-list )  (cond ( (null guest-list)  NIL ) ; Reached the end of the guest list.  ( (member (car guest-list) enemies)  (car guest-list)) ; The first guest is an enemy.  ( T  (identify-enemy (cdr guest-list) ) )  ) ; end of cond  ) ; end of defun

51 Martin and the Dragon  Martin: Tonight, the guest comes in subgroups. Can you identify the names of the enemies?  ((Micky SnowWhite) Bishop (BlackKnight WhiteKnight) RoboCop ( (SirLancelot Modred) Magician) )  Dragon: I will only tell you whether the first one in the list is an enemy or not!

52 Recursion on Both Head and Tail  (defun identify-enemy ( guest-list )  (cond ( (null guest-list)  NIL ) ; Reached the end of the guest list.  ( (listp (car guest-list)) ; If the first element is a list  (append (identify-enemy (car guest-list))  (identify-enemy (cdr guest-list))) )  ( (member (car guest-list) enemies)  ; add to the list of enemies identified from the rest of guests  (cons (car guest-list)  (identify-enemy (cdr guest-list) ) ))  ( T  (identify-enemy (cdr guest-list) ) )  ) ) ; end of defun

53 Keys to Program Recursive Functions  Find out how to solve simple special cases –How to handle empty list? –Are all possible ways to terminate the recursion considered?  Break the task down into smaller subtasks (e.g., using recursion on CDR/CAR)  Know how to synthesize partial solutions generated by subtasks into an overall solution. (e.g., using CONS)  Don't forget to put in termination conditions.

54 LET  How to declare local variables?  (LET ( ( ) ...  ( ) )  ...  )  LET creates and initializes each local variables to its value concurrently, then evaluates expressions sequentially.  It returns the result of evaluating the last expression.  The default value of local variables declared by LET is NIL.  The variables are only visible within the scope of the LET block.

55 LET - Example  >(let ((a 1) (b 2) (c 3)) (list a b c))  (1 2 3)  >(defun solve-quadratic (a b c) ; AX^2 + BX + C = 0  (let ((d (- (* b b) (* 4 a c))))  (if (< d 0)  'complex-roots  (let ((e (sqrt d)))  (list (float (/ (+ (* -1 b) e) (* 2 a)))  (float (/ (+ (* -1 b) (* -1 e)) (* 2 a))))))))  SOLVE-QUADRATIC   >(solve-quadratic 1 3 -1) ; X^2 + 3X + -1 = 0  (0.30277563773199456 -3.3027756377319948)

56 LET - Example (2)  Is the situation of the party likely to be safe for King Arthur?  (defun is-safe-p ( guests )  (let ( (friendly-guests nil)  (hostile-guests nil) )  (setq friendly-guests (identify-friends guests))  (setq hostile-guests (identify-enemy guests))  (> (length friendly-guests)  (length hostile-guests) )  ) )

57 FORMAT  The most flexible method for printing. –Very much like printf in C. –Must give the symbol T as the first argument.  Instead of using %, LISP uses a ~ and a letter to indicate argument types. –~S symbols or S-expressions~D integers –~F floats~A characters or strings –~% newline  Also can set field widths (See detail manual)  >(defun response (name)  (format t "Good morning, ~S. How are you?~%" name)  nil) ; actual return value  RESPONSE  >(response 'dave)  Good morning, DAVE. How are you?  NIL

58 FORMAT (2)  > (defun analyze (n)  (format t "The square of ~D is ~D.~%" n (square n))  (format t "The square-root of ~D is ~F.~%" n (sqrt n))  n) ; return value  ANALYZE  >(analyze 6)  The square of 6 is 36.  The square-root of 6 is 2.449489742783178.  6

59 Functions as Arguments  EVAL  APPLY  Mapping Functions

60 EVAL  (EVAL ) invokes the evaluation procedure  > (EVAL (LIST ‘+ 4 5))  9  > (SETQ A ‘X)  X  > (SETQ X 100)  100  > (CONS (EVAL A) (CONS A ‘( A ) ) )  ?

61 EVAL (2)  How to use EVAL in a learning program?  Suppose we want to learn the description of a cup.  Examples of a cup:  (has-handle container light glass)  (has-handle container light plastic) ....  Examples of a non-cup:  (has-handle container heavy metal) ....  A cup description learned :  (has-handle container light)

62 EVAL (3)  Using EVAL to create function at run-time  Create a function to recognize cups based on the description learned:  (defun create-cup-recognizer (cup-description)  (eval (list ‘defun ‘cup-recognizer ‘(obj)  (list ‘subset  (list ‘quote cup-description)  ‘obj)  )))  Subset tests whether the first arg is a subset of the second arg.  > (create-cup-recognizer cup-def)  cup-recognizer

63 APPLY  (APPLY )  >(APPLY ‘CONS ‘( A ( B C ) ) )  (A B C)  > (APPLY ‘CAR ‘( (A B C) ) )  A  > (SETQ OP ‘+)  +  > (APPLY OP ‘( 5 3 ) )  8  > (SETQ OP ‘-)  -  > (APPLY OP ‘( 5 3 ) )  2

64 APPLY (2)  Suppose we want to “do something” to an enemy identified, but the action is determined at run time (based on their actions, degree of threats, etc.).  > (defun action (fn enemy)  > (defun seize (person).... )  > (defun kill (person)... )  > (defun drunk (person)... )  > (action ‘seize ‘BlackKnight )

65 FUNCALL  (FUNCALL...)  Given a reference to a function, can dynamically invoke it via FUNCALL  > (FUNCALL ‘CONS ‘A ‘( B C ) )  (A B C)  > (FUNCALL ‘CAR ‘(A B C) )  A  > (SETQ OP ‘+)  +  > (FUNCALL OP 5 3)  8  > (SETQ OP ‘-)  -  > (FUNCALL OP 5 3)  2

66 MAPCAR  What if we want to apply a function to an entire list?  (MAPCAR )  > (MAPCAR ‘+ ‘(1 2 3 4) ‘(100 200 300 400) )  (101 202 303 404)  > (SETQ action ‘drunk)  DRUNK  > (SETQ hostile-guests (identify-enemy guests))  > (MAPCAR action hostile-guests)

67 MAPCAR (2)  >(mapcar 'sqrt '(1 2 3 4))  (1.0 1.4142135623730951 1.7320508075688772 2.0)  >(mapcar 'cons '(a b c) '((1 2) (3 4) (5 6)))  ((A 1 2) (B 3 4) (C 5 6))

68 REMOVE, REMOVE-IF  REMOVE deletes all instances of an element from a list.  Works with numbers as well as symbols.  > (remove 'b '(a b c))  (A C)  REMOVE-IF takes a function and a list, and deletes every element from the list that satisfies the function (evaluates to non-NIL).  > (remove-if #'null '(a nil b nil c))  (A B C)

69 69 Slide made by Bogju Lee Summary  IF, PROGN  COND  AND, OR, NOT  Recursive Functions  LET  FORMAT  EVAL  APPLY  FUNCALL  MAPCAR  REMOVE

70 70 Slide made by Bogju Lee Outline  LAMBDA  LISP Practice  LET  SORT  LOOP  Structures  Inheritance  Towers of Hanoi  FIND  DEFMACRO  CLOS

71 LAMBDA  LAMBDA - An anonymous function  When to use it? –It is typically used for defining a function that is needed only in a specific situation. –When write a temporary function for which you do not need to give a name  (LAMBDA (...)....)  #'(lambda (x y) (+ (/ x 2) (/ y 3)))  How to invoke it? –It is typically invoked by EVAL, APPLY, FUNCALL, or mapping functions.

72 LAMBDA (2)  Want to remove any symbols from a list if they are in a certain group (e.g. *word-list*)  > (setf *word-list* '(one once two twice three thrice))  (ONE ONCE TWO TWICE THREE THRICE)  > (remove-if #'(lambda (x) (member x *word-list*)) '(once upon a time there were three bears))  (UPON A TIME THERE WERE BEARS)

73 LAMBDA (3)  One-argument function that returns T when the input is equal to -1  > (defun special-comparison (x) (= x -1))  > #'(lambda (x) (= x -1))  Defun is an overkill  If we need a quick reference, LAMBDA is better  >(mapcar #'(lambda (x) (= x -1)) '(1 2 -1 4 - 1))  (NIL NIL T NIL T)

74 LAMBDA (4)  > (MAPCAR (lambda (x) (+ x bonus)) salary- list)  Can it also appear in the position of a function? –Yes, because LISP thinks LAMBDA forms are functions  > ( (lambda (x) (cond....... )) guest-list )

75 LAMBDA (5)  Understanding LAMBDA form  Viewing it as a function with a name you imagined.  ( @@@@.... (lambda.............. ) ###... )  ( @@@@... ###... )

76 LISP Practice  Set VAR-1 to the integer 5 –> (setf var-1 5) –5  set VAR-2 to the integer 8 –> (setf var-2 8) –8  evaluate 5 divided by 8 –> (/ 5 8) –5/8  convert it from rational to floating point –> (float (/ 5 8)) –0.625  set VAR-3 to VAR-1 divided by VAR-2 –> (setf VAR-3 (/ VAR-1 VAR-2)) –5/8

77 LISP Practice (2)  Compare the equality of VAR-3 with the floating point value above –> (= VAR-3 (float (/ 5 8))) –T  If 5 and 8 were the sides of a right triangle, compute the length of the hypotenuse –> (sqrt (+ (* 5 5) (* 8 8))) –9.4339811320566032  Set LST-1 to be the empty list –> (setf LST-1 nil) –NIL  Set LST-2 to be the list of symbols: red, green, and blue –> (setf LST-2 '(red green blue)) –(RED GREEN BLUE)  Get the first symbol in LST-2 –> (first LST-2) –RED

78 LISP Practice (3)  Get the second symbol in LST-2 –> (second LST-2) –GREEN  Get everything in LST-2 except the first symbol –> (rest LST-2) –(GREEN BLUE)  Set LST-3 to LST-2 with the symbol for maroon added to the front –> (setf LST-3 (cons 'maroon LST-2) –(MAROON RED GREEN BLUE)  Compute the reverse of LST-3 –> (reverse LST-3) –(BLUE GREEN RED MAROON)  Test the equality of LST-3 with its reverse –> (equal lst-3 (reverse lst-3)) –NIL

79 LISP Practice (4)  Compute the reverse of the reverse of LST-3 –> (reverse (reverse lst-3)) –(MAROON RED GREEN BLUE)  Test the equality of LST-3 with the reverse of its reverse –> (equal lst-3 (reverse (reverse lst-3))) –T  What is the last element in LST-3? –> (last LST-3) –BLUE  What is the length of LST-3? –> (length LST-3) –4  What are the middle two elements of LST-3? –> (reverse (rest (reverse (rest LST-3)))) –(RED GREEN)

80 LISP Practice (5)  Create a new list from LST-3, where the same elements appear in order twice –> (append LST-3 LST-3) –(MAROON RED GREEN BLUE MAROON RED GREEN BLUE)  Determine if BLUE is a member of the doubled list –> (member 'blue (append LST-3 LST-3)) –T  Set LST-4 to a list of strings for the same names as the colors in LST-3 –> (setf LST-4 (list "maroon" "red" "green" "blue")) –("maroon" "red" "green" "blue")  Determine if the fourth member of LST-4 is "blue" –> (string= (nth 3 LST-4) "blue") –T

81 81 Slide made by Bogju Lee LET*  (LET* ( ( )  ( ) )  ...  )  If you supply initial values, let* allows the com piler to do the assignments sequentially one lo cal variable can depend on a previous one.

82 82 Slide made by Bogju Lee SORT  (sort )  –basically a greater-than or less-than function –operates on entries of the type in –It should be a function of 2 arguments –Return T if they are in order, NIL otherwise.  > (setq Test '(1 2 3 4 3 2 1))  (1 2 3 4 3 2 1)  > (setq Test (sort Test #'>))  (4 3 3 2 2 1 1)  > (setq Test (sort Test #'<))  (1 1 2 2 3 3 4)

83 83 Slide made by Bogju Lee LOOP  (loop for from to [by ] do...) –> (loop for I from 1 to 3 do (print I)) –1 –2 –3 –> (loop for I from 1 to 5 by 2 do (print I)) –1 –3 –5  (loop for in do...) –> (loop for Entry in '(A B C) do (print Entry))  A  B  C

84 84 Slide made by Bogju Lee LOOP (2)  (loop repeat do...) –> (loop repeat 2 do (print "Hello")) –"Hello"  (loop until do...) –> (setq X 10) –> (loop until (> X 12) do – (setq X (+ X 1)) – (print X)) –11 –12 –13  (loop while do...) –> (setq X 10) –> (loop while (<= X 12) do – (setq X (+ X 1)) – (print X)) –11 –12 –13

85 85 Slide made by Bogju Lee WITH, FINALLY, RETURN  WITH: Declares variables local to the loop. > (setq X 7) (loop with (X) for I from 1 to 5 do (setq X (* I I)) finally (return X)) 25 ; the value of the local X  RETURN –> (loop for I from 1 to 10 do – (print I) – (if (> I 2) (return "Done")) ) –1 –2 –3

86 86 Slide made by Bogju Lee COLLECTING and SUMMING  COLLECTING creates a list and returns it as th e value of the loop. SUMMING adds up a total and returns it as the value of the loop  > (loop for I from 1 to 5 collecting (* I I))  (1 4 9 16 25)  > (loop for I from 1 to 5 summing (* I I))  55

87 87 Slide made by Bogju Lee Structures  (defstruct Name Slot1 Slot2 Slot3...)  > (defstruct Submarine Course Speed Depth) –Creates a function name make-Submarine –Accepts initialization keywords :Course, :Speed, and :Dept h. –> (setq Sub-1 (make-Submarine :Course 90 :Speed 5.5 : Depth 200)) –Also creates slot lookup functions Submarine-Course, Sub marine-Speed, and Submarine-Depth –Slot setting functions (setf Submarine-Course), (setf Subm arine-Speed) and (setf Submarine-Depth). –> (Submarine-Course Sub-1) ==> 90 –> (setf (Submarine-Course Sub-1) 270) –> (Submarine-Course Sub-1) ==> 270 –> (type-of Sub-1) ==> SUBMARINE –> (typep Sub-1 'Submarine) ==> T

88 88 Slide made by Bogju Lee Default Values to Slots  (defstruct Name (Slot1 Default-Val1) (Slot2 Default-Val 2)...)  > (defstruct Submarine  (Course 0)  (Speed 5.0)  (Depth 300))  > (setq Sub-1 (make-Submarine :Speed 5.5 :Depth 200))  > (Submarine-Course Sub-1)  0  > (Submarine-Speed Sub-1)  5.5

89 89 Slide made by Bogju Lee Simple Inheritance  (defstruct (Name (:include Parent)) Slot-Descr iptions)  > (defstruct (Kilo (:include Submarine)) (Class 'Kilo))  > (setq Kilo-1 (make-Kilo :Speed 6.2 :Depth 150))  > (Kilo-Class Kilo-1)==> KILO  > (Kilo-Speed Kilo-1)==> 6.2  > (Submarine-Speed Kilo-1)==> 6.2  > (type-of Kilo-1)==> KILO  > (typep Kilo-1 'Kilo)==> T  > (typep Kilo-1 'Submarine)==> T

90 90 Slide made by Bogju Lee Some Conventions  “*” for global variables –Variable names like *print-pretty* and *Self-Eval* –"*" is a perfectly legal part of a variable name in Lisp –Lisp does not enforce to use “*” for global variables. –just a programmer convention  put "+" around constants –Constants are declared via DEFCONSTANT –cannot be changed at run-time –must be declared before they are used –> (defconstant +Half-Pi+ (/ pi 2.0))

91 91 Slide made by Bogju Lee Towers of Hanoi  Problem description –Three pegs 1, 2, 3. –Move disks in start peg to goal peg.  > defun Towers (Number-of-Discs Start-Peg Goal-Peg)  (cond  ((= 1 Number-of-Discs) (format t “~%Move Top Disc from peg ~D to peg ~D.” Start-Peg Goal-Peg))  (t (Towers (1- Number-of-Discs) Start-Peg  (Remaining-Peg Start-Peg Goal-Peg))  (Towers 1 Start-Peg Goal-Peg)  (Towers (1- Number-of-Discs)  (Remaining-Peg Start-Peg Goal-Peg)  Goal-Peg))))  ;; Given two peg numbers, what is the peg number of the third peg?  > (defun Remaining-Peg (Peg1 Peg2)  (- 6 Peg1 Peg2))

92 92 Slide made by Bogju Lee Towers of Hanoi - Running  ;Yes, Marty? (towers 1 1 2)  ;Move Top Disc from peg 1 to peg 2.  ;NIL  ;Yes, Marty? (towers 2 1 2)  ;Move Top Disc from peg 1 to peg 3.  ;Move Top Disc from peg 1 to peg 2.  ;Move Top Disc from peg 3 to peg 2.  ;NIL  ;Yes, Marty? (towers 3 1 2)  ;Move Top Disc from peg 1 to peg 2.  ;Move Top Disc from peg 1 to peg 3.  ;Move Top Disc from peg 2 to peg 3.  ;Move Top Disc from peg 1 to peg 2.  ;Move Top Disc from peg 3 to peg 1.  ;Move Top Disc from peg 3 to peg 2.  ;Move Top Disc from peg 1 to peg 2.  ;NIL

93 93 Slide made by Bogju Lee FIND  (find ) –"is Entry in List?“ –Returns the first matching element instead of "t“. –> (if (find 3 '(1 2 3 4)) 'Yes 'No) ==> YES –> (find 4 '(1 2 3 4 5)) ==> 4  (find :test ) –"is there an element of List such that Entry and that eleme nt are related by Predicate? –Return the first such element –(find 3 '(2 4 6 8) :test #' 4  Lists and strings are not comparable by "eq“ –> (find '(A B) '((A B) (C D) (E F)) ==> NIL  Use a :test of #'equal for lists or strings are embedded –> (find '(A B)'((A B) (C D) (E F) :test #'equal) –(A B)

94 94 Slide made by Bogju Lee FIND (2)  (find :key ) –"is there an element of List such that Entry is eq to F unction element? –return the first such element if so. –(find 2 '((1 2) (2 3) (3 4)) :key #'second) ==> (1 2)  :test may be combined with :key –> (find A '((A B) (C D E) (F G H I)) :key #'first) ==> (A B) –> (find 3 '((A B) (C D E) (F G H I)) :key #'length) = => (C D E) –> (find '(D E) '((A B) (C D E) (F G H I)) :key #'rest : test #'equal) ==> (C D E)

95 95 Slide made by Bogju Lee DEFMACRO  Lisp macros take Lisp code as input, and retur n Lisp code.  Executed at compiler pre-processor time.  The resultant code gets executed at run-time.  > (defmacro Square (X)  '(*,X,X))

96 96 Slide made by Bogju Lee CLOS  Common Lisp Object System – A powerful OO P package

97 97 Slide made by Bogju Lee DEFCLASS  (defclass Class-Name (Superclass*)  (Slot-Definition*)  Class-Option*)  Empty superclass list, empty slot definition list, no class options  > (defclass Graphical-Object ( )  ( ))  One superclass, two slot definition lists, no class options  > (defclass Rectangle (Graphical-Object)  ((Height :accessor Height :initarg :Height :initfor m 3)  (Width :accessor Width :initarg :Width :initfor m 5)))  One superclass, no slots, one class option.  > (defclass Square (Rectangle)  ( )  (:documentation "The SQUARE class"))

98 98 Slide made by Bogju Lee MAKE-INSTANCE  makes an actual object of that class.  (defclass Submarine ()  ((Depth)  (Speed)))  The slot-value retrieves and sets values of slot s  > (setq Sub-1 (make-instance 'Submarine))  > (setf (slot-value Sub-1 'Depth) 100)  > (slot-value Sub-1 'Depth)  100  > (slot-value Sub-1 'Speed)  [Error: unbound slot SPEED]

99 99 Slide made by Bogju Lee Slot Definitions  :initform a default value for the slot (unbound otherwise )  :reader the name of a function to lookup the slot  :writer the name of a function to set the slot  :accessor the name of a function to read, and (with setf ) set the slot  :initarg the name of a keyword for make-instance  :allocation whether slot is shared or specific to each inst ance  :type a Common Lisp type for use in compiler optimizati ons  :documentation documentation for the very rarely-seen slot object

100 100 Slide made by Bogju Lee :INITFORM  Specifies a default initial value for the slot.  Evaluated each time make-instance is called.  Initial value at make-instance time (see :initar g) override this  > (defclass Submarine ()  ((Depth :initform 100)  (Speed :initform 5)))  > (setq Sub-1 (make-instance 'Submarine))  > (slot-value 'Sub-1 'Speed) ==> 5  > (slot-value 'Sub-1 'Depth) ==> 100

101 101 Slide made by Bogju Lee :READER  Specifies the name of a function that will read the slot  Using :accessor obviates the need for :reader or :writer.  > (defclass Submarine ()  ((Depth :reader Depth :initform 100)  (Speed :reader Speed :initform 5)))  > (setq Sub-1 (make-instance 'Submarine))  > (Depth Sub-1) ==> 100  > (Speed Sub-1) ==> 5

102 102 Slide made by Bogju Lee :WRITER  Specifies the name of a function that will set the slot  Using :accessor obviates the need for :reader or :writer.  > (defclass Submarine ()  ((Depth :reader Depth :writer Set-Depth :initform 10 0)  (Speed :reader Speed :writer Set-Speed :initform 5) ))  > (setq Sub-1 (make-instance 'Submarine))  > (Depth Sub-1) ==> 100  > (Speed Sub-1) ==> 5  > (Set-Depth 200 Sub-1)  > (Set-Speed 4 Sub-1)  > (Depth Sub-1) ==> 200  > (Speed Sub-1) ==> 4

103 103 Slide made by Bogju Lee :ACCESSOR  Specifies the name of a function that will both read and (with setf) set the slot.  If you have a :accessor, you don't need to specify either :reader or :writer.  > (defclass Submarine ()  ((Depth :accessor Depth :initform 100)  (Speed :accessor Speed :initform 5)))  > (setq Sub-1 (make-instance 'Submarine))  > (Depth Sub-1) ==> 100  > (Speed Sub-1) ==> 5  > (setf (Depth Sub-1) 200)  > (setf (Speed Sub-1) 4)  > (Depth Sub-1) ==> 200  > (Speed Sub-1) ==> 4

104 104 Slide made by Bogju Lee :INITARG  Specifies a keyword that can be passed to make-instanc e to give a slot an initial value.  Overrides any default initial value that :initform provide d.  (defclass Submarine ()  ((Depth :accessor Depth :initarg :Depth :initform 100)  (Speed :accessor Speed :initarg :Speed :initform 5)))  (setq Sub-1 (make-instance 'Submarine :Depth 200))  (Depth Sub-1) ==> 200  (Speed Sub-1) ==> 5

105 105 Slide made by Bogju Lee :ALLOCATION  Specifies whether a slot's value is specific to each instan ce (:instance), or has a single value that is shared by all instances of that class (:class)  > (defclass Submarine ()  ((Depth :accessor Depth :initform 100)  (Speed :accessor Speed :initform 5)))  > (defclass Los-Angeles (Submarine)  ((Max-Speed :accessor Max-Speed :initform 10 :alloc ation :class)))  > (setq SSN-1 (make-instance 'Los-Angeles))  > (setq SSN-2 (make-instance 'Los-Angeles))  > (Max-Speed SSN-1) ==> 10  > (Max-Speed SSN-2) ==> 10  > (setf (Max-Speed SSN-1) 15)  > (Max-Speed SSN-1) ==> 15  > (Max-Speed SSN-2) ==> 15

106 106 Slide made by Bogju Lee :TYPE  Specifies a Common Lisp type for the value of the slot.  Used by the compiler to provide optimizations  The :type entry gets inherited by combining the type re strictions of the current class and all superclasses  A class cannot relax a type restriction imposed by a sup erclass, only make it more stringent.  > (defclass Submarine () ((Depth :type integer)))  > (defclass SSN (Submarine) ((Depth :type fixnum)))

107 107 Slide made by Bogju Lee Class Options  :documentation –- documentation for the class object  :default-initargs –- default values for the previously specified :initarg's

108 108 Slide made by Bogju Lee :DEFAULT-INITARGS  Supplies default values for :initarg entries.  Overrides any local or inherited :initform.  The values are evaluated every time make-instance is c alled.  (defclass Submarine ()  ((Depth :accessor Depth :initarg :Depth :initform 100)  (Speed :accessor Speed :initarg :Speed :initform 5)))  (defclass Slow-Submarine (Submarine)  ( )  (:default-initargs  :Speed 1))  (setq Sub-1 (make-instance 'Slow-Submarine))  (Speed Sub-1) ==> 1

109 109 Slide made by Bogju Lee Summary  LAMBDA  LISP Practice  LET  SORT  LOOP  Structures  Inheritance  Towers of Hanoi  FIND  DEFMACRO  CLOS


Download ppt "1 LISP (Lecture Note #7) 인공지능 이복주 단국대학교 컴퓨터공학과. 2 Slide made by Bogju Lee Outline  What is LISP  Variables and Functions  Data Types  SETF  Math."

Similar presentations


Ads by Google