cs 380 artificial intelligence introduction to lisp · lisp introduction functional language: •...
TRANSCRIPT
CS 380ARTIFICIAL INTELLIGENCE
INTRODUCTION TO LISPSantiagoOntañó[email protected]
LISPintroduction
LISPintroduction
LISP1958
LISPintroduction
SHRDLU:https://www.youtube.com/watch?v=bo4RvYJYOzI
(ReadingaboutSHRDLUasakidmademewanttostudyAI!)
LISPintroduction
Functionallanguage:• Avoidschangingstate:i.e.,variableshaveonevalue,
andonevalueonly(youdon’tchangevalueofvariablesonceyouassignthem).• Inreality,youcan(Lispisnotpurelyfunctional).But
thisshouldbeavoided.• ExpressionsvsStatements:infunctionalprogramming,
thereturnvalueofafunctionshoulddependONLYonthevalueofitsparameters.Unlikeinimperativelanguages,wheretherecanbeglobalstate.
• RecursionvsIteration:loopingisimplementedusingrecursion,insteadofiteration.
LISPintroduction
Inventedin1958byJohnMcCarthy(sameguywhocoinedtheterm“ArtificialIntelligence”)
Whatdoes“LISP”standfor??LISt Processing
Simplerepresentationandmanipulationoflists‘(A E I O U)
LISPintroduction
Whatdoes“LISP”standfor??
LISt Processing
Simplerepresentationandmanipulationoflists(let ((vowels ‘(A E I O U))))
A E I O U
NIL
LISPontux.cs.drexel.edu
MIT/GNUSchemeisinstalledontux.cs.drexel.edumit-scheme
Toquit(quit) or (exit)
Youcanloadfilesfromthecurrentdirectory(load “filename”)
CommonLispisinstalledontux.cs.drexel.educlisp
Toquit(quit) or (exit)
Youcanloadfilesfromthecurrentdirectory(load “filename”)
LISPintroduction
peanut
NIL
Primitiveelements:atoms andlists• atoms:peanutbutterjelly“astring”58• lists:(atomsand/orlists)
(peanut butter jelly)
(peanut butter (marshmallow jelly))
NILbutter
marshmallow jelly
Math
AllfunctioncallsinLISPfollowthepattern(function_name arg1 arg2 arg3 ...)
> (+ 2 3)5> (- 5 7)-2> (* 6 7)42
Imperativelanguage:f(x)LISP:(fx)
meansapplyfunctionftoargumentx
Lists
Let’ssaywewanttocreateastaticlistwithnumbers1to5:> (print (1 2 3 4 5))???
Inalist,firstelementisexpectedtobeafunctionwhichusesremainingelementsasarguments.
Ifthelistis“data”insteadofa“functioncall”suppressevaluationwith‘(quote)
Lists
Let’ssaywewanttocreateastaticlistwithnumbers1to5:> (print (1 2 3 4 5))Errorsince1isnotafunction!!!
> (print ‘(1 2 3 4 5))
Inalist,firstelementisexpectedtobeafunctionwhichusesremainingelementsasarguments.
Ifthelistis“data”insteadofa“functioncall”suppressevaluationwith‘(quote)
Lists
Inalist,firstelementisexpectedtobeafunctionwhichusesremainingelementsasarguments.
Ifthelistis“data”insteadofa“functioncall”suppressevaluationwith‘(quote)
Anotherwayisusingthefunction“list”,whichcreatesalistwithallofitsremainingarguments,e.g.: (list 1 2 3)
Lists
Inalist,firstelementisexpectedtobeafunctionwhichusesremainingelementsasarguments.
Ifthelistis“data”insteadofa“functioncall”suppressevaluationwith‘(quote)
Anotherwayisusingthefunction“list”,whichcreatesalistwithallofitsremainingarguments,e.g.: (list 1 2 3)
So,whatifwewanttocreatealistwith3numberslikethis?:(print ‘(1 2 (+ 10 20)))
Lists
Inalist,firstelementisexpectedtobeafunctionwhichusesremainingelementsasarguments.
Ifthelistis“data”insteadofa“functioncall”suppressevaluationwith‘(quote)
Anotherwayisusingthefunction“list”,whichcreatesalistwithallofitsremainingarguments,e.g.: (list 1 2 3)
So,whatifwewanttocreatealistwith3numberslikethis?:(print ‘(1 2 (+ 10 20)))
Doesn’tworkasexpectedsincethequotepreventsevaluation!(print (list (1 2 (+ 10 20))))
Lists(extractinformation)
Getthefirstelement (head)(car '(5 6 7 8))
Gettherestofthe list(tail)(cdr '(5 6 7 8))
A E I O U
NILvowels:
> (car vowels)A> (cdr vowels)(E I O U)
> (car (cdr vowels))E
> (cadr vowels)E
Lists(extractinformation)
Getthefirstelement (head)(car '(5 6 7 8))
Gettherestofthe list(tail)(cdr '(5 6 7 8))
A E I O U
NILvowels:
> (car vowels)A> (cdr vowels)(E I O U)
> (car (cdr vowels))E
> (cadr vowels)E
“car” and“cdr” arefor“hardcore”lisppurists.Ihavealwaysused“first”and“rest”,whichare
moreintuitivetome.
Lists(concatenation)CONS
(let* ((L '(peanut butter jelly))(J (cons ‘apple L)))
(print J))
GivenalistLandanitemx(eitheranatomoralist)(consxL)returnsanewlistwithxasfirstelementandLasrest(Lisunaffected)
> (apple peanut butter jelly)
peanut
NIL
butter jelly
L
apple
J Itdoesnot createanewcopyofalistargument
Code=Data
Lispdoesnotdistinguish“code”from“data”.Forexample:
(let ((a ‘(+ 3 4))(print a) ;usingthecontentofaasdata(eval a) ;usingthecontentofaascode
)
Youcaneasilywritecodethat:• writes/modifiesitself• passfunctions(orevenpartiallydefinedfunctions)as
parameters• etc.
Aboutequality
eq:comparestwoatoms,orwhethertwopointerspointtothesamelocation.equal:compareswhethertwostructureshaveidenticalformandvalues.
(setf x '(a (b c) 1 2 3)) (setf y (car (cdr x))) (setf z (cdr x)) (setf w (car z)) (eq y w) ‘returns T (eq y ‘(b c)) ‘returns NIL (equal y ‘(b c)) ‘returns T
Iamusing“setf”(assignment) inthisslide, forsimplicity, inrealLispprogram,youshould
minimizetheuseof“setf”,anduse“let” instead.
Aboutequality(setf x '(a (b c) 1 2 3)) (setf y (car (cdr x))) (setf z (cdr x)) (setf w (car z)) (eq y w) ‘returns T (eq y ‘(b c)) ‘returns NIL (equal y ‘(b c)) ‘returns T
NIL
NIL
a
b c
1 2 3
x
z
yw
NIL
b c
Additionalfunctions
Functiondoesnotneedtobegivenaname.( (lambda (x) (+ x x)) 7)
Definelocalvariablesforuseinanexpression(let ((a 4)
(b 7)) (+ a b))
Applyafunctiontoeveryelement inalist.(defun square(x)(*xx))=>SQUARE(mapcar 'square'(12345))=>(1491625)
Conditionalexpressions
Theifstatementtakesthree inputs. Ifthefirstargumentistrueisreturnsthesecondotherwise isreturnsthethird.
(if (< 1 3) 4 5)
Thecond extendstheifstatementtoanunlimitednumberofcases.
(cond((< 4 5) 5)((> 4 7) 10)(T 11)
)
CASE(conditional)
CASEislikeC’s“switch”Thevij args aren’tevaluatedotherwise isoptionalandislikeC’sdefault
(case x ((v11 v12 . . .) expr11 expr12 ...)((v21 v22 . . .) expr21 expr22 ...)...(otherwise expr1 expr2 ...))
(setf day4)(caseday
(1(formatt"~%Monday"))(2(formatt"~%Tuesday"))
…(7(formatt"~%Sunday")))
DefinefunctionsThedefun commandcanbeusedfordefiningfunctions.
(defun name (arg list)expression)
Noloops(nottrue).Everything asrecursivefunction.Example:.
(defun fib (n)(if (< n 3)
1(+ (fib (- n 1))
(fib (- n 2)))))
Onceafunctionisdefinedwecanapplyittoarguments.(fIB 6) <- not case sensitive!!!
Recursionreview
DefineLASTfunction
(cond(<test> <result>)(<test> <result>)...(T <result>))
(defun <name> (<arg list>)<expression>)
(NULL x) True iff x is NIL
Recursionreview
Define(LASTL)function
(defun LAST (L)(cond ((NULL L) NIL)
((NULL (cdr L)) L)(T (LAST (cdr L)))))
Define(MEMBERXL)function(useEQUAL)
Recursionreview
Define(LASTL)function
(defun LAST (L)(cond ((NULL L) NIL)
((NULL (cdr L)) L)(T (LAST (cdr L)))))
Define(MEMBERXL)function(useEQUAL)(member2'(123))=>(23)
(defun MEMBER (X L)(cond ((NULL L) NIL)
((EQUAL X (car L)) L)(T (MEMBER X (cdr L)))))
Numericfunctions
+,*,/ plus,times,divide (/ (* 2 3 4) (+ 3 1)) ⇒ 6
- minus (- (- 3) 2) ⇒ –5
sqrt squareroot (sqrt 9) ⇒ 3
exp,expt exponentiation (exp 2) ⇒ e2(expt 3 4) ⇒ 81
log logarithm (log x) ⇒ ln x(log x b) ⇒ logb x
min,max minimum,maximum (min -1 2 -3 4 -5 6) ⇒ –5
abs,round absoluteval,round (abs (round -2.4)) ⇒ 2
truncate integerpart (truncate 3.2) ⇒ 3
mod remainder (mod 5.6 5) ⇒ 0.6
sin,cos,tan trigfuncs (radians) (sin (/ pi 2) ⇒ 1.0
Listfunctions
nth nthelement,nstartsat0
(nth 2 '(a b c d)) ⇒ c
length #ofelements (length '((a b) c (d e))) ⇒ 3
cons concatenation (cons 'a '(b c d)) ⇒ (a b c d)(cons '(a b) 'c) ⇒ ((a b) . c)
list makealist (list (+ 2 3) '(b c) 'd 'e)⇒ (5 (b c) d e)
append appendlists (append '(a) '(b c) '(d))⇒ (a b c d)
(append '(a) '(b c) 'd)⇒ (a b c . d)
reverse reversealist (reverse '((a b) c d)) ⇒ (d c (a b))
Predicates
numberp,integerp,stringp,characterp,evenp,oddp
Testwhetherarg isanumber,integer,string,character,etc.
(numberp 5.78) ⇒ T(integerp 5.78) ⇒ NIL(characterp #\a) ⇒ T
listp,atom,null,consp
Test whetherarg isalist,atomempy/noempty list
(listp nil) ⇒ T(consp nil) ⇒ NIL
<,<=,=,>=,> numericcomparisons arg mustbe anumberstring<,string<=, ... stringcomparisons args must bestring or chareq,equal equalitytests (setf x '(a))
(eq x x) ⇒ T(eq x '(a)) ⇒ NIL(equal x '(a)) ⇒ T
and,or,not logicalpredicates;notandnullareidentical
(not (evenp 8)) ⇒ NIL(and 3 'foo T) ⇒ T
Sequentialexecution(progn e1 e2 ...en)evaluatese1,e2,...,en,andreturnsthevalueofen(prog1e1 e2 ...en)evaluatese1,e2,...,en,andreturnsthevalueofe1
let*assignsinitialvaluessequentially(let* ((x1 v1) (x2 v2) (x3 v3))
e1 e2 ... en)
(let ((x1 v1))(let ((x2 v2))
(let ((x3 v3))e1 e2 ... en)))
Formattedoutput(format <destination> <control-string> <args>) islikeprintf inC
> (setf x "foo")> (format t "~a is ~a~%" 'x x)
X is fooNIL
destinationiswheretosendtheoutputt⇒ sendtostandardoutput,thenreturnNIL
control-stringislikeaprintf controlstringinC~%isanewlinelike\ninC~amatchesanyLispexpression
Loops(dotimes (i num [value]) expressions)executesexpressionswithi =0,...,num −1,thenreturnsvalueorNIL(dolist (x list [value]) expressions)executesexpressionswithx=eachelementoflist,thenreturnsvalueorNIL(return value) returnsvaluefromthemiddleofaloop
(setq result nil)(dotimes (foo 5 (reverse result))
(push foo result)) ⇒ (0 1 2 3 4)
(setq result nil)(dolist (foo '(a 1 b 2 "stop here" 3 z 33))
(if (stringp foo) (return result))(push foo result)) ⇒ (2 B 1 A)
Loops(do ((i1 start1 incr1) . . . (in startn incrn))(termination-test [expressions to evaluate at termination])expression1. . .expressionn)Somewhat likeC’s“for”,buttheiterationvariablesarelocal,andaresetsimultaneously.Tosetthemsequentially, replacedowithdo*Unfortunately, thesyntaxisabitpainful
(setf c 0)(do ((a 1 (+ a 1)) ; a = 1, 2, 3, ...
(b '(1 10 3 2) (cdr b))) ; take successive cdrs((null b) c) ; if b is empty, return c
(setf c (+ c (expt (car b) a)))) ; add x^a to c
⇒ compute 11 + 102 + 33 + 24 = 144
Loops(loop [loop clauses])iterationmacrowithahugenumberofoptions
Becareful!complexcasescanbehardtounderstand(seeANSICommonLisp,pp.239-244)
Butsimplecasesareeasiertounderstandthandois:
(setf c 0)(do ((a 1 (+ a 1))
(b '(1 10 3 2) (cdr b))) ((null b) c)
(setf c (+ c (expt (car b) a))))
⇒ compute 11 + 102 + 33 + 24 = 144
(loop for a from 1 by 1for b in '(1 10 3 2)sum (expt b a))
Lisp• Functionalprogramminglanguagemixedwithlotsofimperative
functionality.
• Data=code
• Veryconvenienttomanipulatesymbols,lists,etc.
• Syntaxwasdefinedinthe50s,wherecomputingpowerwaslimited.So,itis“computerfriendly”,butnotvery“humanfriendly”unlesswepaycloseattentiontoourprogrammingstyle.• Lispletsuswriteverynastylookingprogramsifnotbeing
careful!!!
• UsedinmostearlyAIsoftware