Lecture 18 LISP
Lecture 18 LISP
LISP
• Invented by John McCarthy (1958)
• Two simple data structure (atoms and lists)
• Heavy use of recursion
• Interpretive language
• Variations
– Scheme
– Common Lisp (de facto industrial standard)
• Most widely used AI programming language
• Functional Programming Paradigm
• Low maintenance overhead
Valid Objects
• Atoms may be;
• Numbers: (real 1.0, integer 1)
• Symbols: a consecutive sequence of characters (no space)
e.g. a, x, price-of-beef
• Two special symbols: T and NIL for logical true and false
> (+ 1 3 5)
9
> (/ 3 5)
3/5
>Command
(/ 3.0 5)Line Prompt
0.59999999999999998
> (sqrt 4)
2
Evaluation of S-expression
1) Evaluating an atom
• Numerical and string atoms evaluate to themselves
• Symbols evaluate to their values if they are assigned
values, otherwise return Error
• The values of T and NIL are themselves
Evaluation of S-expression
2) Evaluate a list - evaluate every top element of the list
as follows, unless explicitly forbidden:
• The first element is always a function name;
evaluating it means to call the function body
• Each of the rest elements will then be evaluated, and
their values returned as the arguments for the
function
Evaluation of S-expression
• Examples :
3/5+4
> (+ (/ 3 5) 4)
23/5
> (+ (sqrt 4)
4.0)
6.0
> (sqrt x)
Error: The variable
X is unbound
Evaluation of S-expression
3) To assign a value to a symbol use: setq, set, setf
>y
3.0
> (+ x y)
6.0
• To forbid evaluation of a symbol use: quote or ’
> (quote
x)
x
> 'x
x
> (setq z
'x)
x
Functions
• Math functions
– +, -, *, /, exp, expt, log, sqrt, sin, cos, tan, max, min
> (list 'a 'b 'c) ; making a list with the arguments as its elements
(A B C) ; if a, b, c have values A, B, C, then (list a b c)
; returns list (A B C)
> (append '(a b) '(c d)) ; appends one list in front of another
(A B C D)
Functions (cont’)
• Selectors
– first, rest, nth, car, cdr…
> (first '(a s d f)) ;returns the first element of a list
a
> (rest '((a s) d f)) ;deletes the first element from the
;list and returns the rest as a list
(d f)
> (car L)
; returns the first top level element of list L
A
> (cdr L)
; returns the rest of list L
(B C)