1 lisp (lecture note #7) 인공지능 이복주 단국대학교 컴퓨터공학과. 2 slide made by...
Post on 26-Dec-2015
220 Views
Preview:
TRANSCRIPT
1
LISPLISP(Lecture Note #7)(Lecture Note #7)
인공지능
이복주단국대학교 컴퓨터공학과
2Slide made by Bogju Lee
OutlineOutline
What is LISP Variables and Functions Data Types SETF Math Operations S-expressions CONS Cell …
Slide made by Bogju Lee
What is LISP?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
Slide made by Bogju Lee
Why LISP?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
Slide made by Bogju Lee
Variables and FunctionsVariables 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.
Slide made by Bogju Lee
Data TypesData 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
Slide made by Bogju Lee
Special SymbolsSpecial 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.
Slide made by Bogju Lee
SETFSETF
(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”
Slide made by Bogju Lee
Math OperationsMath Operations
+, -, *, / FLOAT, ROUND, SQRT, EXPT, LOG, EXP
Slide made by Bogju Lee
S-expressionsS-expressions
A list is an S-expression. Nested list is also an S-expression. (1 2 (3 4) 5))
Slide made by Bogju Lee
CONS CellCONS 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 CAR
CDRCDR
Slide made by Bogju Lee
ListList
A linked list always terminates by having the CDR of the last CONS cell pointing to a special symbol: NIL.
Example: (John loves Mary)
John loves Mary
NIL
Slide made by Bogju Lee
CONSCONS
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
Slide made by Bogju Lee
CONS (2)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)
Slide made by Bogju Lee
Nested SublistsNested Sublists
A sublist is a list pointed by a CAR pointer of a CONS cell
Example: ( John loves ( play tennis ) )
John loves
NIL
NIL
play tennis
Slide made by Bogju Lee
CONS (3)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)
Slide made by Bogju Lee
CAR, CDRCAR, 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)
Slide made by Bogju Lee
LISTLIST
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)
Slide made by Bogju Lee
APPENDAPPEND
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)
Slide made by Bogju Lee
Other List FunctionsOther 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)
Slide made by Bogju Lee
EvaluationEvaluation
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
Slide made by Bogju Lee
Evaluation RulesEvaluation 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.
Slide made by Bogju Lee
QuoteQuote
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)
Slide made by Bogju Lee
SETQSETQ
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
Slide made by Bogju Lee
Change BindingChange 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)
Slide made by Bogju Lee
Change Binding (2)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)
Slide made by Bogju Lee
DEFUNDEFUN
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.
Slide made by Bogju Lee
DEFUN (2)DEFUN (2)
>(defun range (n) (cond ((not (numberp n)) 'not-number) ((< n 0) 'negative) ((> n 0) 'positive) (T 'zero))) > (range 52.03) POSITIVE
Slide made by Bogju Lee
DEFUN (3)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)
Slide made by Bogju Lee
Symbol and Function with the Same Symbol and Function with the Same NameName
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)
Slide made by Bogju Lee
PredicatesPredicates
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
Slide made by Bogju Lee
EQ, EQUALEQ, 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
Slide made by Bogju Lee
MEMBERMEMBER
(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
34Slide made by Bogju Lee
SummarySummary
What is LISP Variables and Functions Data Types SETF Math Operations S-expressions CONS Cell …
35Slide made by Bogju Lee
OutlineOutline
IF, PROGN COND AND, OR, NOT Recursive Functions LET FORMAT EVAL APPLY FUNCALL MAPCAR REMOVE
Slide made by Bogju Lee
IF, PROGNIF, 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
Slide made by Bogju Lee
CONDCOND
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 expressio
n associated with the test
Slide made by Bogju Lee
COND - ExampleCOND - Example
(defun select-character (enemy) (cond ( (eq enemy ‘Penguin) ‘Batman) ( (eq enemy ‘Catwoman) ‘J-Bond ) ( (eq enemy ‘Black-Knight) ‘(White-Knight King-Arthur) ) ) )
Slide made by Bogju Lee
COND with T ConditionCOND 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 ) )
Slide made by Bogju Lee
AND, OR, NOTAND, OR, NOT
Binding more complex conditions Simple tests can be combined into a complex one using AND, O
R, NOT. (AND <test1> <test2> ... <testn>) evaluates tests in a left-to-rig
ht 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 t
est (i.e., testn). (Defun safe-caar ( L ) (and (listp L) (listp (car L)) (car (car L)) ) )
Slide made by Bogju Lee
ANDAND
> (safe-caar ‘A) NIL > (safe-caar ‘( ( A ) ) ) A > (caar ‘A) Error!
Slide made by Bogju Lee
OR and NOTOR 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
Slide made by Bogju Lee
Using AND, OR in CONDUsing 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
Slide made by Bogju Lee
Martin and the DragonMartin 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?
Slide made by Bogju Lee
Recursive FunctionsRecursive 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
Slide made by Bogju Lee
Factorial ExampleFactorial 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
Slide made by Bogju Lee
Member ExampleMember Example
Recursion is especially useful for list processing. Many problems can be thought of recursively as applying to eith
er 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
Slide made by Bogju Lee
Fixing the Infinite RecursionFixing 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
Slide made by Bogju Lee
Martin and the DragonMartin 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.
Slide made by Bogju Lee
Building Lists Using RecursionBuilding 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 en
emy. ( T (identify-enemy (cdr guest-list) ) ) ) ; end of cond ) ; end of defun
Slide made by Bogju Lee
Martin and the DragonMartin 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!
Slide made by Bogju Lee
Recursion on Both Head and TailRecursion 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
Slide made by Bogju Lee
Keys to Program Recursive FunctionsKeys 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.
Slide made by Bogju Lee
LETLET
How to declare local variables? (LET ( ( <var1> <val1> ) ... ( <vark> <valk> ) ) <exp1> ... <expN> ) LET creates and initializes each local variables to its value concu
rrently, 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.
Slide made by Bogju Lee
LET - ExampleLET - 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)
Slide made by Bogju Lee
LET - Example (2)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) ) ) )
Slide made by Bogju Lee
FORMATFORMAT
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
Slide made by Bogju Lee
FORMAT (2)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
Slide made by Bogju Lee
Functions as ArgumentsFunctions as Arguments
EVAL APPLY Mapping Functions
Slide made by Bogju Lee
EVALEVAL
(EVAL <exp>) invokes the evaluation procedure
> (EVAL (LIST ‘+ 4 5)) 9 > (SETQ A ‘X) X > (SETQ X 100) 100 > (CONS (EVAL A) (CONS A ‘( A ) ) ) ?
Slide made by Bogju Lee
EVAL (2)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)
Slide made by Bogju Lee
EVAL (3)EVAL (3)
Using EVAL to create function at run-time Create a function to recognize cups based on the des
cription 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 s
econd arg. > (create-cup-recognizer cup-def) cup-recognizer
Slide made by Bogju Lee
APPLYAPPLY
(APPLY <fn-name> <arg-list> ) >(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
Slide made by Bogju Lee
APPLY (2)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 )
Slide made by Bogju Lee
FUNCALLFUNCALL
(FUNCALL <fn-name> <arg1> <arg2> ...) 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
Slide made by Bogju Lee
MAPCARMAPCAR
What if we want to apply a function to an entire list?
(MAPCAR <fn-name> <arg1-list> <arg2-list>) > (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)
Slide made by Bogju Lee
MAPCAR (2)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))
Slide made by Bogju Lee
REMOVE, REMOVE-IFREMOVE, 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)
69Slide made by Bogju Lee
SummarySummary
IF, PROGN COND AND, OR, NOT Recursive Functions LET FORMAT EVAL APPLY FUNCALL MAPCAR REMOVE
70Slide made by Bogju Lee
OutlineOutline
LAMBDA LISP Practice LET SORT LOOP Structures Inheritance Towers of Hanoi FIND DEFMACRO CLOS
Slide made by Bogju Lee
LAMBDALAMBDA
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 (<arg1> <arg2> ...) <exp1> ....) #'(lambda (x y) (+ (/ x 2) (/ y 3))) How to invoke it?
– It is typically invoked by EVAL, APPLY, FUNCALL, or mapping functions.
Slide made by Bogju Lee
LAMBDA (2)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*)) '(o
nce upon a time there were three bears)) (UPON A TIME THERE WERE BEARS)
Slide made by Bogju Lee
LAMBDA (3)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)
Slide made by Bogju Lee
LAMBDA (4)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 )
Slide made by Bogju Lee
LAMBDA (5)LAMBDA (5)
Understanding LAMBDA form Viewing it as a function with a name you
imagined. ( @@@@ .... (lambda .............. ) ###... )
( @@@@ ... <imaginary-fn-name> ### ... )
Slide made by Bogju Lee
LISP PracticeLISP 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
Slide made by Bogju Lee
LISP Practice (2)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
Slide made by Bogju Lee
LISP Practice (3)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
Slide made by Bogju Lee
LISP Practice (4)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)
Slide made by Bogju Lee
LISP Practice (5)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
81Slide made by Bogju Lee
LET*LET*
(LET* ( ( <var1> <val1> ) ( <vark> <valk> ) ) <exp1> ... <expN> ) If you supply initial values, let* allows the
compiler to do the assignments sequentially one local variable can depend on a previous one.
82Slide made by Bogju Lee
SORTSORT
(sort <List> <Predicate>) <Predicate>
– basically a greater-than or less-than function – operates on entries of the type in <List>– 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)
83Slide made by Bogju Lee
LOOPLOOP
(loop for <I> from <N1> to <N2> [by <N3>] 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 <Entry> in <List> do ...)– > (loop for Entry in '(A B C) do (print Entry))
A B C
84Slide made by Bogju Lee
LOOP (2)LOOP (2) (loop repeat <X> do ...)
– > (loop repeat 2 do (print "Hello"))– "Hello"– "Hello"
(loop until <Condition> do ...)– > (setq X 10)– > (loop until (> X 12) do– (setq X (+ X 1))– (print X))– 11– 12– 13
(loop while <Condition> do ...)– > (setq X 10)– > (loop while (<= X 12) do– (setq X (+ X 1))– (print X))– 11– 12– 13
85Slide made by Bogju Lee
WITH, FINALLY, RETURNWITH, 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
86Slide made by Bogju Lee
COLLECTING and SUMMINGCOLLECTING and SUMMING
COLLECTING creates a list and returns it as the 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
87Slide made by Bogju Lee
StructuresStructures
(defstruct Name Slot1 Slot2 Slot3...)
> (defstruct Submarine Course Speed Depth)– Creates a function name make-Submarine– Accepts initialization keywords :Course, :Speed,
and :Depth. – > (setq Sub-1 (make-Submarine :Course 90 :Speed
5.5 :Depth 200)) – Also creates slot lookup functions Submarine-Course,
Submarine-Speed, and Submarine-Depth– Slot setting functions (setf Submarine-Course), (setf
Submarine-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
88Slide made by Bogju Lee
Default Values to SlotsDefault Values to Slots
(defstruct Name (Slot1 Default-Val1) (Slot2 Default-Val2) ...)
> (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
89Slide made by Bogju Lee
Simple InheritanceSimple Inheritance
(defstruct (Name (:include Parent)) Slot-Descriptions)
> (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
90Slide made by Bogju Lee
Some ConventionsSome 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))
91Slide made by Bogju Lee
Towers of HanoiTowers 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))
92Slide made by Bogju Lee
Towers of Hanoi - RunningTowers 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
93Slide made by Bogju Lee
FINDFIND
(find <Entry> <List>)– "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 <Entry> <List> :test <Predicate>) – "is there an element of List such that Entry and that
element 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)
94Slide made by Bogju Lee
FIND (2)FIND (2)
(find <Entry> <List> :key <Function>) – "is there an element of List such that Entry is eq to
Function 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)
95Slide made by Bogju Lee
DEFMACRODEFMACRO
Lisp macros take Lisp code as input, and return Lisp code.
Executed at compiler pre-processor time. The resultant code gets executed at run-time.
> (defmacro Square (X) '(* ,X ,X))
96Slide made by Bogju Lee
CLOSCLOS
Common Lisp Object System – A powerful OOP package
97Slide made by Bogju Lee
DEFCLASSDEFCLASS (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 :initform 3) (Width :accessor Width :initarg :Width :initform
5))) One superclass, no slots, one class option. > (defclass Square (Rectangle) ( ) (:documentation "The SQUARE class"))
98Slide made by Bogju Lee
MAKE-INSTANCEMAKE-INSTANCE
makes an actual object of that class. (defclass Submarine () ((Depth) (Speed)))
The slot-value retrieves and sets values of slots
> (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]
99Slide made by Bogju Lee
Slot DefinitionsSlot 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
instance :type a Common Lisp type for use in compiler
optimizations :documentation documentation for the very rarely-seen
slot object
100Slide made by Bogju Lee
:INITFORM:INITFORM
Specifies a default initial value for the slot. Evaluated each time make-instance is called. Initial value at make-instance time
(see :initarg) 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
101Slide made by Bogju Lee
:READER: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
102Slide made by Bogju Lee
:WRITER: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
100) (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
103Slide made by Bogju Lee
:ACCESSOR: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
104Slide made by Bogju Lee
:INITARG:INITARG
Specifies a keyword that can be passed to make-instance to give a slot an initial value.
Overrides any default initial value that :initform provided.
(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
105Slide made by Bogju Lee
:ALLOCATION:ALLOCATION Specifies whether a slot's value is specific to each
instance (: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 :allocation :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
106Slide made by Bogju Lee
:TYPE: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 restrictions of the current class and all superclasses
A class cannot relax a type restriction imposed by a superclass, only make it more stringent.
> (defclass Submarine () ((Depth :type integer))) > (defclass SSN (Submarine) ((Depth :type fixnum)))
107Slide made by Bogju Lee
Class OptionsClass Options
:documentation – - documentation for the class object
:default-initargs – - default values for the previously specified :initarg's
108Slide made by Bogju Lee
:DEFAULT-INITARGS:DEFAULT-INITARGS Supplies default values for :initarg entries. Overrides any local or inherited :initform. The values are evaluated every time make-instance is
called.
(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
109Slide made by Bogju Lee
SummarySummary
LAMBDA LISP Practice LET SORT LOOP Structures Inheritance Towers of Hanoi FIND DEFMACRO CLOS
top related