1.1k likes | 1.27k Views
LISP (Lecture Note #7). 인공지능 이복주 단국대학교 컴퓨터공학과. Outline. What is LISP Variables and Functions Data Types SETF Math Operations S-expressions CONS Cell …. What is LISP?. A LISt Processing language The basic data structure is linked list A functional programming language
E N D
LISP(Lecture Note #7) 인공지능 이복주 단국대학교 컴퓨터공학과
Outline • What is LISP • Variables and Functions • Data Types • SETF • Math Operations • S-expressions • CONS Cell • … Slide made by Bogju Lee
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
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
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.
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
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.
SETF • (SETF <variable> <expression> • 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”
Math Operations • +, -, *, / • FLOAT, ROUND, SQRT, EXPT, LOG, EXP
S-expressions • A list is an S-expression. • Nested list is also an S-expression. • (1 2 (3 4) 5))
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. CDR CDR CAR CAR
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) NIL John loves Mary
NIL Mary 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)
CONS (2) • Using CONS to insert an item to the front of a list • (CONS <item to be inserted> <a list>) • 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)
NIL John loves NIL play tennis Nested Sublists • A sublist is a list pointed by a CAR pointer of a CONS cell • Example: ( John loves ( play tennis ) )
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)
CAR, CDR • List access • (CAR <a list>) returns the first element of the list. • (CDR <a list>) 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)
LIST • Other list creating functions • (LIST <item1> <item2> ... <itemN>) returns a list • whose first element is <item 1>, second element is • <item 2>, ...., Nth element is <itemN>. • 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)
APPEND • Concatenating lists • (APPEND <list 1> <list 2>) returns a list that is the result of concatenating <list 1> and <list 2>. • > (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)
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)
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
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.
Quote • Quote symbol ‘ is a short hand for a function QUOTE • (QUOTE <arg>) • 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)
SETQ • Assignment and binding • A symbol (variable) can be assigned a value (called its binding) using SETQ. • (SETQ <symbol-name> <anything>) • 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
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)
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)
DEFUN • A function is defined using DEFUN • (DEFUN <fn-name> (<arg1> ...<argK>) <exp1> ... <expN> ) • 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.
DEFUN (2) • >(defun range (n) • (cond ((not (numberp n)) 'not-number) • ((< n 0) 'negative) • ((> n 0) 'positive) • (T 'zero))) • > (range 52.03) • POSITIVE
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)
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)
Predicates • Functions that return ``true’’ (i.e., T) or ``false’’ (i.e., NIL). • type-testing predicates • (NULL <item>) returns T if <item> is NIL (empty list), otherwise NIL. • (LISTP <item>) returns T if <item> is a list, otherwise NIL. • (ATOM <item>) returns T if <item> is an atom (i.e., a symbol, a number, or NIL). • (NUMBERP <item>) returns T if <item> is a number
EQ, EQUAL • Equality-testing Predicates: EQ, =, STRING=, EQUAL • (EQ <item1> <item2>) returns T if two arguments are two identical atoms (symbols and characters). • > (EQ ‘(Banana Apple) ‘(Banana Apple)) • NIL • (= <number1> <number2>) • > (= 5 (/ 10 2)) • T • (STRING= <string1> <string2>) • (EQUAL <item1> <item2>) 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
MEMBER • (MEMBER <item> <list>) returns T if <item> is an atom that is a top-level element of <list>. • > (setq my-friends ‘(MacGyver (Batman Robin)) ) • > (member ‘MacGyver my-friends) • T • > (member ‘Batman my-friends) • NIL • > (member ‘(Batman Robin) my-friends) • NIL
Summary • What is LISP • Variables and Functions • Data Types • SETF • Math Operations • S-expressions • CONS Cell • … Slide made by Bogju Lee
Outline • IF, PROGN • COND • AND, OR, NOT • Recursive Functions • LET • FORMAT • EVAL • APPLY • FUNCALL • MAPCAR • REMOVE Slide made by Bogju Lee
IF, PROGN • Conditional Expression: IF, PROGN • (IF <condition> <expression1> [<expression2>]) • 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 <expression1> <expression2> ..) • 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
COND • COND is an N-branch conditional expression • (COND ( <test1> <exp11> ... <exp1L> ) • ( <test2> <exp21> ... <exp2M> ) • ... • ( <testK> <expK1> ... <expKN> ) ) • 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
COND - Example • (defun select-character (enemy) • (cond ( (eq enemy ‘Penguin) • ‘Batman) • ( (eq enemy ‘Catwoman) • ‘J-Bond ) • ( (eq enemy ‘Black-Knight) • ‘(White-Knight King-Arthur) ) • ) • )
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 • ) • )
AND, OR, NOT • Binding more complex conditions • Simple tests can be combined into a complex one using AND, OR, NOT. • (AND <test1> <test2> ... <testn>) 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)) • ) )
AND • > (safe-caar ‘A) • NIL • > (safe-caar ‘( ( A ) ) ) • A • > (caar ‘A) • Error!
OR and NOT • (OR <test1> <test2> ... <testn>) 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 <exp>) returns T if <exp> is NIL, returns NIL if <exp> is non-NIL. • > (NOT (NULL ‘(A B C) ) ) • T
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
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?
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
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
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
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
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.
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