You are on page 1of 73

LISP: A Brief Overview

What is Lisp?
A functional language includes linked
lists as a built-in data type
Everything in lisp is either an atom or
a list (expression)
Lisp is dynamically typed
It is possible to define executable
data structures because data and
code are equivalent

Basic
terminology

Atoms: word-like indivisible objects which can be numbers or


symbols.
Atoms have both names and values
Often times in Lisp programming you will work with the name and
ignore the value
Literal atoms ,Letters (upper, lower cases)
begin with letter
value is undefined when created
a or Sam
Numeric atoms
(name matches value) 12 or 1.53
Numbers: 3.1416

Characters : * + - / @ $ % ^ & _ < > ~ .


Examples
Hyphenated-name
nil
x

Lists: sentence-like objects formed from atoms or


other lists, and enclosed in parentheses.

Consider the list (a b c)


a is an atom, b is an atom, c is an atom
S-expressions: compositions of atoms and lists.
Procedures: step by step specifications how to do
something.
Primitives: procedures supplied by the LISP itself
example: (+ 5 6)
User-defined procedures: procedures introduced by
the programmer.
Program: a collection of procedures working together.

Pre-Defined Literal Atoms


T or t
True (logical constant)

Nil or nil
Nil = ( ) meaning the "empty list
False (logical constant)

There are no reserved words in Lisp to that


means t or nil can be redefined by the user

Using Lisp
Lisp is a interactive system
You can files to be processed as a batch
file, but more often than not the
programmer is the main program
Every expression typed a the > prompt
is read and evaluated unless it is
prefixed with an apostrophe
Typing (exit) at the > prompt terminates
the xlisp program

Sample Output
>(a b c)
error: unbound function - a
if continued: try evaluating symbol again
1> [ back to top level ]
> '(a b c)
(a b c)
> 1
1
> 1.2
1.2
> a
error: unbound variable - a
if continued: try evaluating symbol again
1> [ back to top level ]

Sample Output
> nil
nil
> t
t
> T
t
> '(a (b c) d)
(a (b c) d)
> (setq sam 'abc)
abc
> sam
abc

Characteristics
of LISP

1. Language for artificial intelligence programming


a. Originally designed for symbolic computing

2. Imperative language

a. Describe how to perform an algorithm


b. Contrasts with declarative languages such as PROLOG

3. Functional programming

a. Syntax and semantics are derived from the mathematical theory


of recursive functions.
b. Combined with a rich set of high-level tools for building symbolic
data structures such as predicates, frames, networks, and
objects

4. Popularity in the AI community

a. Widely used as a language for implementing AI tools and models


b. High-level functionality and rich development environment make
it an ideal language for building and testing prototype systems.

Symbolic
Why do we care about symbols?
Understand human cognition with a
language like symbolic processing

Why LISP?
Especially designed for symbol
manipulation.
Provides built-in support for lists
(everything is a list..)
Automatic storage management (no need
to keep track of memory allocation).
Interactive environment, which allows
programs to be developed step by step.
That is, if a change is to be introduced, only
changed functions need to be recompiled.

WHAT MAKES LISP


DIFFERENT
1.
2.
3.
4.
5.
6.

Built-in support for Lists.


Automatic memory management.
Dynamic typing.
First-class functions.
Uniform syntax.
Extensibility

Interpreted &
interactive
Interpreted
Interactive

USER(1): 12
12
USER(2): (+ 12 3)
15
USER(3): (setf Almost-age
31)
31
USER(4): Almost-age
31
USER(5): 'Almost-age
ALMOST-AGE

SPECIAL FORMS:
1. Forms not evaluated according
to the evaluation rule.
2. Special forms:
defun, defparameter, setf, let,
case, if, function, quote.

OTHER DATA TYPES


1. Strings: (length "abc") --> 3
2. Many number types.

LISP EVALUATION RULE


1. Every expression is either a list or an atom.
2. Every list to be evaluated is either a special form or a function
application.
3. A special form expression is a list whose first element is a special
form operator and is evaluated according to the special rule of
that operator.
4. A function application is evaluated by first evaluating the
arguments (the rest of the list) and then finding the function
named by the first element of the list and applying it to the list of
evaluated arguments.
5. Every atom is either a symbol or a non-symbol.
6. A symbol evaluates to the most recent value assigned to the
variable.
7. A non-symbol atom evaluates to itself.

Read-Eval-Print
Interactive Environment

User enters s-expressions


LISP interpreter prints a prompt

If you enter
Atom: LISP evaluates itself (error if nothing is
bound to the atom)
List: LISP evaluates as an evaluation of
function, i.e. that the first item in the list
needs to be a function definition (error if no
function definition is bound for the first atom),
and remaining elements to be its arguments.
> (* 7 9)
63

Control of LISP
Evaluation:
quote & eval

quote :
prevent the evaluation of arguments

(quote a) ==> a
(quote (+ 1 3)) ==> (+ 1 3)
a ==> a
(+ 4 6) ==> (+ 4 6)

eval
allows programmers to evaluate sexpressions at will
(eval (quote (+ 2 3))) ==> 5
(list * 2 5) ==> (* 2 5)
(eval (list * 2 5)) ==> 10

car=first and cdr=rest


> (car '(a b c))
a
> (cdr '(a b c))
(b c)
> (car nil)
nil
> (cdr nil)
nil
> (first '(a b c))
a
> (car (cdr '(a b c)))
b
> (cadr '(a b c))
b

eval and quote


> (eval (cdr '(a + 2 3)))
5
> (setq a 'b)
b
> a
b
> b
error: unbound variable - b
if continued: try evaluating symbol
again
1> [ back to top level ]
> (set 'a 'b)
b
> (eval (eval ''a))
b
> 'a
a

eval and quote


> (eval (eval '(quote a)))
b
> 'a
a
> (eval '(list '* 9 6))
(* 9 6)
> (eval (eval '(list * 9 6)))
error: bad function - (* 9 6)
1> [ back to top level ]
> (eval (eval '(list '* 9 6)))
54

LISTS
1. Primitive aggregating type.
2. Primitive functions: first, second, ...,
length, last. append, cons, list.

List and S-expression


List

A sequence of either atoms or other lists


separated by blanks and enclosed in
parentheses.
Example

(1 2 3 4)
(a (b c) (d (e f)))

Empty list ( ) : nil

nil is the only s-expression that is considered to be


both an atom and a list.

S-expression

An atom is an s-expression.
If s1, s2,, sn are s-expressions,
then so is the list (s 1 s2 sn).

Everything's a List!
Data
Functions

(a b c)
(defun plus (x y)
(+ x y))

Simple syntax:
(function-name arg1 arg2 )

List Functions
> (list 'a 2 'b)
(a 2 b)
> (list '(a b) '(c d))
((a b) (c d))
> (list sam c)
error: unbound variable - c
if continued: try evaluating symbol again
1> [ back to top level ]
> (list sam 'c)
(abc c)
> (cons 'a '(b c d))
(a b c d)
> (cons '(a b c) 'd)
((a b c) . d)

List Functions
> (append '(a b) '(c d))
(a b c d)
> (reverse '(a b c d))
(d c b a)
> (length '(a (b c) d)))
3
>
> (last '(a b c d))
(d)
> (subst 'a 'b '(a b c))
(a a c)
> (subst 'a 'b '(a b c b))
(a a c a)

List as recursive
structures
Cons cell: data structure to hold a list in LISP
car - holds the first element.
cdr - holds the rest in the list.

Accessing a list

(car (a b c)) ==> a


(cdr (a b c)) ==> (b c)
(first (a b c)) ==> a
(second (a b c)) ==> b
(nth 1 (a b c)) ==> b

Constructing a list
(cons a (b c)) ==> (a b c)
(cons a nil) ==> (a)
(cons (a b) (c d)) ==> ((a b) c d)

Artificial Intelligence

27

Nested lists, structure,


car/cdr recursion
More list construction
(append (a b) (c d)) ==> (a b c d)
(cons (a b) (c d)) ==> ((a b) c d)

Counting the number of elements in the list


(length ((1 2) 3 (1 (4 (5))))) ==> 3

Artificial Intelligence

28

Name Calling
Lisp remembers function names
separately from variable names
USER(22): (defun add (x y) (+ x y))
ADD
USER(23): (setf add 9)
9
USER(24): add
9
USER(25): #'add
#<Interpreted Function ADD>

S-expressions
An s-expression can have other s-expressions nested in it.
Examples:
(+

(* 5

7) ( / 2 4))

Expressions can be interpreted both, procedurally and


declaratively.
If interpreted procedurally, an expression provides a
direction for doing something. Such an expression is called
a form, and its first element is the name of a procedure to
be used to produce the value.
The process of computing the value of an expression is
called evaluation.
If interpreted declaratively, expressions represent data.

Data and procedures have the same syntax.

Evaluation of
atoms

The value of a number is the number itself.


Example: 5 ==> 5

The value of a string is the string itself.


Example: Nice day ==> Nice day

The value of the symbol T is T (true).


The value of the symbol NIL is NIL (false).
The symbol NIL and the empty list ( ) are the same thing.
Variables are names of memory locations. The contents
stored in a given memory cell is the value of the variable
serving as a name of this location.
Example: Let x be a variable, and 5 be the contents of the
memory cell called x. Then, the value of x is 5.

Numbers

Integers: 179, 45
Ratio: 5/7, 7/9
Floating point: 5.2, 7.9
Examples:
* (/ 25 5)
5
* (/ 46 9)
46/9
; do not divide evenly
* (float (/ 46 9))
5.111111
* (round (/ 46 9))
5
; the nearest integer
1/9
; the remainder

Arithmetic Functions
> (/ 2 3)
2/3
> (/ 1.0 2)
0.5
> (1+ 3)
4
> (mod 2 3)
2
> (mod 5 2)
1
> (+ (* 2 2) (/ 4.0 5)
)
4.8

More numeric
primitives
* (- 6)
-6
* (- -6)
6
* (max 5 7 2)
7
* (min 5 7 2)
2
* (sqrt (* (+ 1 3) (* 2 2)))
4.0
* (+ (round (/ 22 7)) (round (/ 7
3)))
5

* (+ 2 2.5)
4.5
* (expt 3 6)
729
* (sqrt 81)
9.0
* (sqrt 82)
9.055386
* (abs 6)
6
* (abs -6)
6

Bindin
g
variabl

Binding variables:
set(1/2)
(setq <symbol> <form>)
bind <form> to <symbol>
<symbol> is NOT evaluated.

(set <place> <form>)


replace s-expression at <place> with <form>
<place> is evaluated. (it must exists.)

(setf <place> <form>)


generalized form of set: when <place> is a symbol, it behaves like
setq; otherwise, it behaves like set.

Binding variables: set(2/2)


Examples of set / setq
(setq x 1) ==> 1 ;;;
(set a 2) ==> ERROR!!
(set a 2) ==> 2 ;;;
(+ a x) ==> 3
(setq l (x y z)) ==>
(set (car l) g) ==> g
l ==> (g y z)

assigns 1 to x
;;; a is NOT defined
assigns 2 to a
(x y z)

Examples of setf
(setf x 1) ==> 1
(setf a 2) ==> 2
(+ a x) ==> 3
(setf l (x y z)) ==> (x y z)
(setf (car l) g) ==> g
l ==> (g y z)

Conditional
s&
Predicates

Decision
Decision making structures require
that the programmer specify one or
more conditions to be evaluated or
tested by the program, along with a
statement or statements to be
executed if the condition is
determined to be true, and optionally,
other statements to be executed if the
condition is determined to be false.
Artificial Intelligence

39

If Macro
The if macro is followed by a test
clause that evaluates to t or nil. If the
test clause is evaluated to the t, then
the action following the test clause is
executed. If it is nil, then the next
clause is(ifevaluated.
(test-clause)
(action1)
(action2)
)
Artificial Intelligence

40

If Macro Examples
Example 1:
>(setq a 10)
>( if (< a 20)
(* a 10)
)

Example 2:
>(setq myList '(a b c d e f))
> (if (<(length MyList) 10) (cdr myList))

Artificial Intelligence

41

when
The when macro is followed by a test clause that evaluates to t or nil. If the
test clause is evaluated to nil, then no form is evaluated and nil is returned,
however it the test result is t, then the action following the test clause is
executed.
Syntax:
(when (test-clause)
(<action1)
)

Artificial Intelligence

42

when examples
Example1:
>(setq a 10)
> (when (<= a 20) (* a 10) )

Example2:
> (when (<= a 20) (car '(a b c) ))

Artificial Intelligence

43

cond
The cond construct in LISP is most
commonly used to permit branching.
Syntax :
(cond (test1 action1)
(test2 action2) ...
(testn actionn)
)
Artificial Intelligence

44

cond examples
Example 1:
>(setq a 10)
>( cond ( (> a 20) (* a 1) )
( (< a 5) (* a 2) )
( (= a 10) (* a 3) )
)
Example 2:
>(setq day 3)
>(cond ((= day 1) "Sunday")
((= day 2) "Monday")
((= day 3) "Tuesday")
((= day 5) "Thursday")
)
Artificial Intelligence

45

More examples

>(setq mark 90)


>(cond ((>= mark 90)
"Excellent"
)
((>= mark 80)
"Very Good"
)
((>= mark 70)
"good"
)
((< mark 70)
"fail"
)
)
Artificial Intelligence

46

>(setq angle 270)


>(cond ((= angle 90)
"north"
)
((= angle 180)
"east"
)
((= angle 270)
"south"
)
((= angle 360)
"west"
)
)
Artificial Intelligence

47

case
The case construct implements multiple test-action clauses
like the cond construct. However, it evaluates a key form and
allows multiple action clauses based on the evaluation of that
key form.
Syntax:

(case (keyform)
((key1) (action1 action2 ...) )
((key2) (action1 action2 ...) )
...
((keyn) (action1 action2 ...) ))

Artificial Intelligence

48

case Examples
Example1:
> (setq day 3)
> (case day
(1 "Sunday")
(2 "Monday")
(3 "Tuesday")
)
Example2:
>(setq a 10)
>(case a
(0 (* a 0))
(10 (* a 10))
(20 (* a 20))
(30 (* a 30))
)
Artificial Intelligence

49

Iterati
on

Iteration

Loop
Loop for
do
Dotimes
dolist

loop
The loop construct is the simplest form of iteration provided by LISP. In its
simplest form, it allows you to execute some statement(s) repeatedly until it
finds a return statement.
(loop
(<test condition> ) (return
<optional var/val)
[body]
) ;end loop

Artificial Intelligence

52

Loop example
>(setq a 0)
>(loop
(setq a (+ a 1))
(print a)
(when (> a 10) (return a))
)

1
2
3
4
5
6
7
8
9
10
11

Artificial Intelligence

53

Loop for
The loop for construct allows you to implement a for-loop like iteration as most
common in other languages.
Syntax:

(loop for loop-variable in <a list>


do (action)
)
(loop for loop-variable from value1 to
value2
do (action)
)
Artificial Intelligence

54

Example1
A

(loop for x in '(a b c d e)


B
do
C
D
(print x)
E
)

Artificial Intelligence

55

Example 2
(loop for x from 1 to 20
if(= (MOD x 2) 0)
do (print x)
)

Artificial Intelligence

2
4
6
8
10
12
14
16
18
20

56

Do
The do construct is also used for performing iteration
using LISP. It provides a structured form of iteration.

Syntax:
(do (variable1 value1 updated-value1)
(variable2 value2 updated-value2)
(variable3 value3 updated-value3)
...
(test return-value)
(s-expressions)
)

Artificial Intelligence

57

Examples
(do ((x 0 (+ 2 x))
(y 20 ( - y 2)))
((= x y)(- x y))
(format t "~% x = ~d y = ~d" x y)
)
x = 0 y = 20
x
x
x
x

Artificial Intelligence

=
=
=
=

2
4
6
8

y
y
y
y

=
=
=
=

18
16
14
12

58

Dotimes
The dotimes construct allows looping for some fixed
number of iterations.
Example:
(dotimes (n 11)
(print n)
(prin1 (* n n))
)

00
11
24
39
4 16
5 25
6 36
7 49
8 64
9 81
10 100
Artificial Intelligence

0
1
2
3
4
5
6
7
8
9
10

59

Dolist
The dolist construct allows iteration through each element of a list.
Example:
(dolist (n '(1 2 3 4 5 6 7 8 9))
Number: 1 Square: 1
(format t "~% Number: ~d Square:
~d" 2n Square:
(* n n))4
Number:
)
Number: 3 Square: 9
Number:
16
Number:
25
Number:
36
Number:
49
Number:
64
Artificial Intelligence
Number:

4 Square:
5 Square:
6 Square:
7 Square:
8 Square:
9 Square:

60

FUNCTIONS
Syntax of Function Definition

(defun <function-name> (<formal parameters>)


<function body>)

defun : define function

Function
Examples

>(defun square (x)


(* x x)
)

>(defun hypothenuse (x y)
(sqrt (+ (square x)
(square y)
)
)
)
>square 5
> hypothenuse 2 4

Function Definition
> (defun intro (x y)
(list x 'this 'is y)
)
Intro
>; be careful not to quote the arguments when
>; defining the function
> (intro 2 3)
(2 this is 3)
> (intro 'stanley 'livingston)
(stanley this is livingston)

Recursion Example 1
( defun factorial (n)
"Compute the factorial of
n."
(if (= n 1)
1
(* n (factorial (- n 1) ))
)
)
Artificial Intelligence

64

Recursion example 2
(defun fibonacci (N)
"Compute the N'th Fibonacci
number."
(if (or (= N 0) (= N 1))
1
(+ (fibonacci (- N 1)) (fibonacci (- N
2)) )
)
)

Artificial Intelligence

65

Local variables: let


(LET ( ( <var1> <val1> )
...
( <vark> <valk> ) )
<exp1>
...
<expN> )
LET is your way to set up temporary
variables. You can initialize each local
variable to its value concurrently, then
evaluates expressions sequentially. It returns
the result of evaluating the last expression.
The default value of local variables declared
by LET is NIL.

Example 1:
>(setf x 4)
>(let ((x 3))
(print x)
(setf x 9)
(print x)
(print "hello")
)
>(print x)

Example 2:

Predicate Functions
Predicates are functions that test their
arguments for some specific conditions
and returns nil if the condition is false,
or some non-nil value is the condition
is true.

Artificial Intelligence

68

Predicate Examples 1
> (atom 2)
t
> (atom '(a b c))
nil
> (listp 2)
nil
> (listp '(a b c))
t
> (equal 2 3)
nil
> (= 2 3)
nil
> (equal 6 (* 2 3))
t

Predicate Examples 2
> (set a (1 2))
(1 2)
> (equal a (1 2))
t
> (eql a (1 2))
nil
> (null '())
t
> (null 2)
nil
> nil
nil
> (null nil)
t

Predicate Examples 3
(write (atom 'abcd))
(write (equal 'a 'b))
(write (evenp 10))
(write (evenp 7 ))
(write (oddp 7 ))
(write (zerop 0.0000000001))
(write (eq 3 3.0 ))
(write (equal 3 3.0 ))
(write (null nil ))

Artificial Intelligence

71

atom
It takes one argument and returns t if the argument is an atom or nil if otherwise.
equal
It takes two arguments and returns t if they are structurally equal or nil otherwise
eq
It takes two arguments and returns t if they are same identical objects or nil otherwise
eql
It takes two arguments and returns t if the arguments are eq, or if they are numbers of the same type wi
same value, or if they are character objects that represent the same character, or nil otherwise
evenp
It takes one numeric argument and returns t if the argument is even number or nil if otherwise.
oddp
It takes one numeric argument and returns t if the argument is odd number or nil if otherwise.
zerop
It takes one numeric argument and returns t if the argument is zero or nil if otherwise.
null
It takes one argument and returns t if the argument evaluates to nil, otherwise it returns nil.
listp
It takes one argument and returns t if the argument evaluates to a list otherwise it returns nil.
greaterp It takes one or more argument and returns t if either there is a single argument or the arguments are
successively larger from left to right, or nil if otherwise.
lessp
It takes one or more argument and returns t if either there is a single argument or the arguments are
successively smaller from left to right, or nil if otherwise..
numberp It takes one argument and returns t if the argument is a number or nil if otherwise.
symbolp It takes one argument and returns t if the argument is a symbol otherwise it returns nil.
integerp
It takes one argument and returns t if the argument is an integer otherwise it returns nil.
rationalp It takes one argument and returns t if the argument is rational number, either a ratio or a number, otherw
returns nil.
floatp
It takes one argument and returns t if the argument is a floating point number otherwise it returns nil.
realp
It takes one argument and returns t if the argument is a real number otherwise it returns nil.
complexp It takes one argument and returns t if the argument is a complex number otherwise it returns nil.
characterp It takes one argument and returns t if the argument is a character otherwise it returns nil.
stringp
It takes one argument and returns t if the argument is a string object otherwise it returns nil.
arrayp
It takes one argument and returns t if the argument is an array object otherwise it returns nil.
Artificial Intelligence

72

Membership Functions
> (member 'c '(a b c d))
(c d)
> (member 'a '((a b) c d))
nil
> (member '(d e) '((a b) c (d e) f))
nil
> (assoc 'c '((a b) (c d) (e f)))
(c d)

You might also like