Lecture 2: Introduction to LISP
Download
Report
Transcript Lecture 2: Introduction to LISP
Introduction to Artificial Intelligence
Lisp
Ruth Bergman
Fall 2002
LISP
• LISP (List Programming)
– invented by John McCarthy, Stanford, 1958
– interpreted and compiled language
– many firsts (interpreter, garbage collection, debugger ....)
• Basic structure of LISP is the list
– atoms
• quoted representation
–
–
–
–
–
–
cons
nil
car
cdr
null
print representation
LISP Functions
• Lisp expressions
– quoted symbol
– variable
– functions
• The easiest way to understand how Lisp operates is to
understand the interpreter:
– (loop (print (eval (read)))
• read an expression (atom, quoted symbol, or list)
• evaluate that expression
• print the result
LISP Functions
• Lisp expressions
– quoted symbol
– variable
– functions
• Functions are prefix notation
– cons, cdr, cddr, cdddr ...
– arithmetic
– list manipulations (append, list, cons)
• (append ‘(a b) ‘(c d))
• (list ‘(a b) ‘(c d))
• (cons ‘(a b) ‘(c d))
– other lists (subst, last, length)
LISP Variables
• Variables can be declared, or created
dynamically
– (set ‘a ‘b)
– (setq a ‘b)
– (setf a ‘b)
• We can even force evaluation
– (setf a ‘b b ‘c)
– (eval a)
More
Functions/Predicate
• (defun fact (n) (if (= n 1) 1 (* n (fact (1- n)))))
– values passed by value (copies)
– variables are bound or free
– variables are lexically scoped (dynamic is possible)
•
•
•
•
•
numberp
atom
listp
evenp, oddp
and/or/not
Functions are Data
• Notice that a function is just a list; we can manipulate it like data
– (setq fun ‘fact)
– (funcall fun 3) 6
– (apply #’fact ‘(3))
• We can define “anonymous” procedures
– (funcall ‘(lambda (x) (list x)) 3) (3)
– (funcall (list ‘lambda ‘(x) ‘(list x)) 3)
• We can also define local variables
– (defun foo (x)
(let ((a 1) (b 3)) (setq b (* x b)) (list a b x)))
• There are lots of other “function functions”
– map
– reduce
Some exercises
• Define
–
–
–
–
–
–
reverse
flatten
member
union
intersection
difference