Top Banner
CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP Santiago Ontañón [email protected]
37

CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

May 31, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

CS 380ARTIFICIAL INTELLIGENCE

INTRODUCTION TO LISPSantiagoOntañó[email protected]

Page 2: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

LISPintroduction

Page 3: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

LISPintroduction

LISP1958

Page 4: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

LISPintroduction

SHRDLU:https://www.youtube.com/watch?v=bo4RvYJYOzI

(ReadingaboutSHRDLUasakidmademewanttostudyAI!)

Page 5: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

LISPintroduction

Functionallanguage:• Avoidschangingstate:i.e.,variableshaveonevalue,

andonevalueonly(youdon’tchangevalueofvariablesonceyouassignthem).• Inreality,youcan(Lispisnotpurelyfunctional).But

thisshouldbeavoided.• ExpressionsvsStatements:infunctionalprogramming,

thereturnvalueofafunctionshoulddependONLYonthevalueofitsparameters.Unlikeinimperativelanguages,wheretherecanbeglobalstate.

• RecursionvsIteration:loopingisimplementedusingrecursion,insteadofiteration.

Page 6: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

LISPintroduction

Inventedin1958byJohnMcCarthy(sameguywhocoinedtheterm“ArtificialIntelligence”)

Whatdoes“LISP”standfor??LISt Processing

Simplerepresentationandmanipulationoflists‘(A E I O U)

Page 7: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

LISPintroduction

Whatdoes“LISP”standfor??

LISt Processing

Simplerepresentationandmanipulationoflists(let ((vowels ‘(A E I O U))))

A E I O U

NIL

Page 8: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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”)

Page 9: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

LISPintroduction

peanut

NIL

Primitiveelements:atoms andlists• atoms:peanutbutterjelly“astring”58• lists:(atomsand/orlists)

(peanut butter jelly)

(peanut butter (marshmallow jelly))

NILbutter

marshmallow jelly

Page 10: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

Math

AllfunctioncallsinLISPfollowthepattern(function_name arg1 arg2 arg3 ...)

> (+ 2 3)5> (- 5 7)-2> (* 6 7)42

Imperativelanguage:f(x)LISP:(fx)

meansapplyfunctionftoargumentx

Page 11: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

Lists

Let’ssaywewanttocreateastaticlistwithnumbers1to5:> (print (1 2 3 4 5))???

Inalist,firstelementisexpectedtobeafunctionwhichusesremainingelementsasarguments.

Ifthelistis“data”insteadofa“functioncall”suppressevaluationwith‘(quote)

Page 12: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

Lists

Let’ssaywewanttocreateastaticlistwithnumbers1to5:> (print (1 2 3 4 5))Errorsince1isnotafunction!!!

> (print ‘(1 2 3 4 5))

Inalist,firstelementisexpectedtobeafunctionwhichusesremainingelementsasarguments.

Ifthelistis“data”insteadofa“functioncall”suppressevaluationwith‘(quote)

Page 13: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

Lists

Inalist,firstelementisexpectedtobeafunctionwhichusesremainingelementsasarguments.

Ifthelistis“data”insteadofa“functioncall”suppressevaluationwith‘(quote)

Anotherwayisusingthefunction“list”,whichcreatesalistwithallofitsremainingarguments,e.g.: (list 1 2 3)

Page 14: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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)))

Page 15: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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))))

Page 16: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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

Page 17: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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.

Page 18: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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

Page 19: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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.

Page 20: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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.

Page 21: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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

Page 22: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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)

Page 23: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

Conditionalexpressions

Theifstatementtakesthree inputs. Ifthefirstargumentistrueisreturnsthesecondotherwise isreturnsthethird.

(if (< 1 3) 4 5)

Thecond extendstheifstatementtoanunlimitednumberofcases.

(cond((< 4 5) 5)((> 4 7) 10)(T 11)

)

Page 24: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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")))

Page 25: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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!!!

Page 26: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

Recursionreview

DefineLASTfunction

(cond(<test> <result>)(<test> <result>)...(T <result>))

(defun <name> (<arg list>)<expression>)

(NULL x) True iff x is NIL

Page 27: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

Recursionreview

Define(LASTL)function

(defun LAST (L)(cond ((NULL L) NIL)

((NULL (cdr L)) L)(T (LAST (cdr L)))))

Define(MEMBERXL)function(useEQUAL)

Page 28: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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)))))

Page 29: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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

Page 30: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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))

Page 31: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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

Page 32: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’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)))

Page 33: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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

Page 34: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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)

Page 35: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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

Page 36: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

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))

Page 37: CS 380 ARTIFICIAL INTELLIGENCE INTRODUCTION TO LISP · LISP introduction Functional language: • Avoids changing state: i.e., variables have one value, and one value only (you don’t

Lisp• Functionalprogramminglanguagemixedwithlotsofimperative

functionality.

• Data=code

• Veryconvenienttomanipulatesymbols,lists,etc.

• Syntaxwasdefinedinthe50s,wherecomputingpowerwaslimited.So,itis“computerfriendly”,butnotvery“humanfriendly”unlesswepaycloseattentiontoourprogrammingstyle.• Lispletsuswriteverynastylookingprogramsifnotbeing

careful!!!

• UsedinmostearlyAIsoftware