Title: CSCI 2210: Programming in Lisp
1CSCI 2210 Programming in Lisp
2CSCI 2210 Programming in Lisp
- Instructor
- Alok Mehta (mehtaa_at_cs.rpi.edu)
- Office Hours After class or by appointment
- Home Phone (518) 785-7576
- Teaching Assistant
- Course Web Page
- http//www.cs.rpi.edu/courses/spring99/lisp
- Textbook
- Ansi Common Lisp, by Paul Graham Prentice Hall
1996
3Syllabus
4Assignments/Grading
- Assignments/Grading
- HW 1 - Due on January 27 (25)
- HW 2 - Due on February 10 (25)
- HW 3 - Due on March 5 (25)
- Final Exam - March 3 (25)
- Homeworks
- Due at 115959 pm on the due date
- Total of two grace days are given for late
submission - After this, there is a late penalty of 10 points
per day
5What is Lisp?
- Stands for LISt Processing
- An old, different programming language
- Why study Lisp?
- Different, but not outdated
- Simple, elegant syntax and constructs are
extremely simple - Encourages "bottom-up" software development
- Helps make computers intelligent
- Easy to write a program that write programs
- Programs that can modify themselves based on new
knowledge - Artificial Intelligence (AI) uses
6Examples of Lisp Applications
- Some popular programs written in Lisp
- Emacs
- Autocad
- Interleaf
- Other, misc. application areas
- Expert Problem Solvers (e.g. Calculus, Geometry,
etc.) - Reasoning, Knowledge Representation
- Learning
- Education
- Intelligent support systems
- Natural Language interfaces
- Speech
- Vision
7Lisp is Interactive
- Lisp is interactive
- Toplevel - when lisp is waiting for input
- Lisp expressions can be typed into the toplevel
- An expression typed into the toplevel is
evaluated by the Lisp interpreter
gt 1 1 gt
8Atoms and Lists
- Atoms
- A single element of a particular data type
- Examples
- 1
- 3.3
- "This is a String"
- ThisIsASymbol
- Lists
- Lists may contain atoms or other lists
- Examples
- (1 8.1 3)
- (a b (c d) e)
- (73 22 b ("A" x) ((((3.14) (4 7) nil (32)))))
9Expressions
- Expressions
- Either atoms or a list
- Can represent expressions to be evaluated
- Format
- (operator arg1 arg2 )
- Zero or more arguments
- Example
- gt (sqrt 4.0) Take the square root of 4.0
- 2.0
- Can represent data and data structures
- (course CSCI221001
- (name (Programming in Lisp))
- (instructor
- (name (Alok Mehta))
- (email (mehtaa_at_cs.rpi.edu)))
- (department (Computer Science)))
10Expressions are evaluated
- We said
- Lisp expressions can be typed into the toplevel
- An expression typed into the toplevel is
evaluated by the Lisp interpreter - Everything (DATA PROGRAMS) in Lisp is an
expression (i.e. an atom or a list)
gt 1 1 gt (sqrt 4.0) 2.0 gt ( 2 3) Note that
expressions are in prefix notation! 5
11Rules for Evaluation
- An expression is evaluated as follows
- Each argument are evaluated, from left to right
- Call by value occurs for the given operator
- Example gt (/ ( 4 6) 3)
- / is the operator skip this for now
- ( 4 6) is the first argument. Evaluate this
(note the recursion here) - is the operator skip this for now
- 4 is the first argument it evaluates to
itself (4) - 6 is the second argument it evaluates to
itself (6) - is now called, with arguments 4 and 6
passed by value - This evaluates to 24
- We currently have (/ 24 3)
- The second argument to / is 3, this evaluates to
itself (3) - / is called with arguments 24 and 3 passed by
value - (/ 24 3) is replaced by the value 8, which is
returned to the toplevel
12More Expression Examples
gt (/ ( 4 6) 3)8gt ( 1 2 3 4 5) The
operator takes zero or more args15gt ()0gt
"Hello""Hello"gt (sqrt ( 1 3))2.0gt (quote (
1 3)) Exception! Quote Don't evaluate arg(
1 3)gt '( 1 3) shortcut for (quote ( 1
3))( 1 3)
13The Quote Operator
- Special Operator
- Disobeys the evaluation rule
- Does NOT evaluate its argument
gt (sqrt ( 1 3))2.0gt (quote ( 1 3))( 1 3)gt
(quote hello)HELLOgt 'helloHELLOgt helloError
Attempt to take the value of the unbound variable
HELLO'. condition type UNBOUND-VARIABLE
14Symbols
- In the expression below, HELLO is a Symbol
- gt 'hello
- HELLO
- Symbols are used for variables (and other things)
- The following expression causes the interpreter
to search for a value for the symbol HELLO - gt hello
- Error condition type UNBOUND-VARIABLE
- If the symbol HELLO was bound to something, the
value would have been returned - gt (set (quote hello) 3) initialize HELLO to 3
- 3
- gt hello
- 3
15Set, Setf Assign Variables
- Set and Setf assign variables (side effect)
- gt (set (quote a) '( 5 3))
- ( 5 3)
- gt (setf b ( 5 3)) equivalent to (set (quote b)
( 5 3)) - 8
- Examining variables
- gt a
- ( 5 3)
- gt b
- 8
- Accessing variables
- gt ( 3 b)
- 11
- gt ( 3 'b)
- error
- gt ( 3 a)
- error
16Overview of Lisp Syntax
- Overview of Lisp Syntax
- ( Left Parenthesis. Begins a list of items.
Lists may be nested. - ) Right Parenthesis. Ends a list of items.
- ( ( 3 2) ( 7 8))
- Semicolon. Begins a comment (terminates at
end of line) - ( ( 3 2) ( 7 8)) Evaluate ((32)(78))
- " Double Quote. Surrounds character strings.
- "This is a thirty-nine character string."
- Single (Forward) Quote. Dont evaluate next
expression - '(Programming in Lisp)
- Examples
- ( 3 2) returns the string "( 3 2) as an
atom - ( 3 2) evaluates ( 3 2) and returns 5
- '( 3 2) returns the expression ( 3 2) as a
list - Lisp is case-insensitive
17The Story So Far...
- Atoms
- Lists
- Expressions
- The Evaluation Rule
- Symbols
- Set, Setf
- Quote (')
18How to Run Lisp
- Under UNIX (on RCS)
- kcl, gcl
- Specify in homework which was used
- q to recover from an error
- D to exit
- Under Win '95
- Go to http//www.franz.com/dload/dload.html
- Select Allegro CL Lite for Windows
19Using Lisp on RCS
- Conventions
- UNIX Prompt
- gt LISP Interpreter prompt
- From a UNIX prompt, start the lisp interpreter
- gcl
- GCL (GNU Common Lisp) Version(2.2) Mon Sep 30
094544 EDT 1996 - Licensed under GNU Public Library License
- Contains Enhancements by W. Schelter
- gt
- At the Lisp prompt, type your Lisp Expressions
- gt ( ( 3 2) ( 7 8))
- 75
- gt
- Lisp expressions return values
- Return values can be used in other expressions
20Using Lisp on RCS
- Recovering from errors in GCL (q)
- gt ( 4 x)
- Error "x" is not of type NUMBER.
- Fast links are on do (siuse-fast-links nil)
for debugging - Error signalled by .
- Broken at . Type H for Help.
- gtgt q
- Executing lisp commands from a file
- gt (load "prog1.lsp")
- Reads and executes the lisp expressions
contained in prog1.lsp - Accessing on-line help
- gt (help)
- Exiting from GCL (bye) or CTRL-d
- gt (bye)
21How to Write Lisp
- Experiment by entering expressions at the
toplevel - or, Write code into a file and save it
- Lisp code can be messy
- Use an editor with paren matching!
- vi set sm
- emacs M-x lisp-mode
- Load
- Reads a file and executes expressions contained
in the file, as if you typed them directly at the
top level - gt (load "hello.lsp")
- t
- Load returns the result of the LAST expression
evaluated in the lisp file
22Constructing New Lists
- One way Use quote operator
- gt (quote (1 2 3))
- (1 2 3)
- gt '(1 2 3)
- (1 2 3)
- Another way Use the list operator
- gt (list 1 2 3)
- (1 2 3)
- When is one better than another? Depends...
- gt '(1 2 (3 (4)) 5)
- (1 2 (3 (4)) 5)
- gt (list 1 2 (list 3 (list 4)) 5)
- (1 2 (3 (4)) 5)
- gt '(1 2 ( 3 4) 5)
- (1 2 ( 3 4) 5)
- gt (list 1 2 ( 3 4) 5)
- (1 2 7 5)
23Cons, Remove, First, Rest
- Lists are used to represent knowledge
- gt (setf complang '(C Lisp Java Cobol))
- (C LISP JAVA COBOL)
- Cons (CONStruct) adds an element to a list
- gt (setf complang (cons 'Perl complang))
- (PERL C LISP JAVA COBOL)
- Remove removes an element from a list
- gt (setf complang (remove 'Cobol complang))
- (PERL C LISP JAVA)
- First gets the first element of a list
- gt (first complang)
- PERL
- Rest gets everything except the first element
- gt (rest complang)
- (C LISP JAVA)
24Lists are like boxes NILEmpty
G H
C D
F
A B
E
I
J
- Lists are like boxes they can be nested
- ((( A B ) C D ( E ) ( )) ( F ) G H (((I)(J))))
- NIL is an empty list
- gt (setf messy '(((A B) C D (E) ( )) (F) G H
(((I)(J)))) ) - (((A B) C D (E) NIL) (F) G H (((I)(J))))
- gt (first messy)
- ((A B) C D (E) NIL)
25First, Rest Revisited
- First returns the first element of a list
- Returns an atom if the first element is an atom
- Returns a list if the first element is a list
- Rest returns all elements of a list except the
first - Always returns a list
- Examples
- gt (first '((a) b)) returns (A)
- gt (first '(a b)) returns A
- gt (first '(a)) returns A
- gt (first '( )) returns NIL
- gt (rest '((a) b)) returns (B)
- gt (rest '(a b)) returns (B)
- gt (rest '(a)) returns NIL
- gt (rest '( )) returns NIL
26Getting the second element
- Use combinations of first and rest
- gt (setf abcd '(a b c d))
- (A B C D)
- gt (first (rest abcd))
- B
- gt (first '(rest abcd))
- REST Quote stops expression from being
evaluated! - Or, use second
- gt (second abcd)
- B
- third, fourth, , tenth are also defined
27Exercises
- Evaluate
- gt (first '((a b) (c d)))
- gt (first (rest (first '((a b) (c d)))))
- Use First and Rest to get the symbol PEAR
- (apple orange pear grape)
- ((apple orange) (pear grapefruit))
- (apple (orange) ((pear)) (((grapefruit))))
28Setf Revisited
- Setf
- Format
- (setf ltvar1gt ltvalue1gt ltvar2gt ltvalue2gt )
- Example
- gt (setf x 0 y 0 z 2)
- 2
- Returns
- the value of the last element
- Side effects
- assigns values for symbols (or variables) ltvar1gt,
ltvar2gt, - the symbol then becomes an atom that evaluates
the value assigned to it - gt x
- 0
29List storage
- Draw List Storage Diagram for
- (setf alist '(A B C))
- Explain semantics of functions
- first, rest, cons, remove
- Draw List Storage diagram for
- (apple (orange pear) grapefruit)
A B C
alist
Contents of Address Register (CAR) Old name for
First
Contents of Decrement portion of Register (CDR)
Old name for Rest
C
B
A
alist
Cons Cell
30Append, List
- Append
- Combines the elements of lists
- gt (append (a b c) (d e f))
- (A B C D E F)
- List
- Creates a new list from its arguments
- gt (list a b (c))
- (A B (C))
A
B
C
D
E
F
31Cons, Setf Push Pop
- Cons has no side effects
- gt (setf complang '(C Lisp Java Cobol))
- (C LISP JAVA COBOL)
- gt (cons Perl complang)
- (PERL C LISP JAVA COBOL)
- gt complang
- (C LISP JAVA COBOL)
- gt (setf complang (cons Perl complang))
- (PERL C LISP JAVA COBOL)
- gt complang
- (PERL C LISP JAVA COBOL)
- Push/Pop - Implement a stack data structure
- Push - shortcut for adding elements permanently
- Pop - shortcut for removing elements permanently
- gt (push complang Fortran)
- (FORTRAN PERL C LISP JAVA COBOL)
- gt (pop complang)
- (PERL C LISP JAVA COBOL)
32T, NIL
- Lisp uses the symbols T and NIL for boolean
values - T True
- NIL False (also means Empty List)
- These are reserved symbols and can't be
re-assigned - Note that NIL is used to mean both an empty list
and a false - gt 'nil
- NIL
- gt nil
- NIL
- The symbol NIL evaluates to itself
- gt '()
- NIL
- Functions that determine truth are called
predicates
33Predicates listp
- Listp Is the argument a list?
- gt (listp 'Hello)
- NIL
- gt (listp '(1 2 3))
- T
- gt (listp nil)
- T
- NIL is a list with zero elements, but is still
considered a list! - gt (listp '())
- T
- gt (listp '(HELLO))
- T
- gt (listp (HELLO))
- Error
- gt (listp '( 1 2 3))
- T
- gt (listp ( 1 2 3))
- NIL
34Predicates null, not
- Null Is the argument an empty list?
- gt (null nil)
- T
- gt (null t)
- NIL
- gt (null 3.4)
- NIL
- gt (null '(1 2 3))
- NIL
- Not Returns the opposite of argument
- gt (not nil)
- T
- gt (not t)
- NIL
- gt (not '(1 2 3))
- NIL
- Not and Null are equivalent
35If
- If is a macro
- Macros do not follow the Lisp evaluation rule
- Syntax (if ltpredicategt ltthen-partgt ltelse-partgt)
- Evaluates the first argument, ltpredicategt
- If the first argument is true, the second
argument is evaluated - Otherwise, if the first argument is NIL, the
third argument is evaluated - Example
- (if (gt a b) a b) returns maximum of a and b
36And/Or
- And/Or
- Macros (don't follow Lisp evaluation rule)
- Lazy evaluation
- stop evaluating once you know the answer
- may not evaluate all arguments
- Return the value of the LAST argument evaluated
- And
- Returns true if all arguments are true stops at
first false statement - Or
- Returns true if any argument is true stops at
first true statement
37Procedure Declaration
- Simple procedure in C/C to square a number
- double sqr (double x)
- return x x
-
- Equivalent function in Lisp
- (defun sqr (x) ( x x))
- Note
- C/C implementation is strongly typed Lisp is
not - Value returned by procedure is the last
expression evaluated - (defun sqr (x)
- ( 2 3)
- ( 7 8)
- ( x 3)
- ( x x))
38Defun
- Defun is a Lisp macro for DEfining FUNctions
- (defun ltproc-namegt
- (ltparameter1gt ltparameter2gt ...)
- ltexpression1gt ltexpression2gt ...)
- Side effect
- defines a user-defined lisp procedure
- Returns the name of the procedure defined
- Defun does not evaluate its arguments
- Resulting user-defined procedure is used like any
other Lisp procedure - gt (defun sqr (x) ( x x))
- SQR
- gt (sqr 5)
- 25
39Output
- So far the toplevel prints return values
- But, need a general way to print
- E.g. the load procedure only prints the return
value of the last expression - Print, Format
- gt (print 3)
- 3
- 3
- gt (defun verbose-add (a b)
- (format t "A plus A equals A." a b ( a
b)) - ( a b))
- gt (verbose-add 3 5)
- 3 plus 5 equal 8
- 8
40Input
- Read
- gt (defun askem (prompt)
- (format t "A" prompt)
- (read))
- ASKEM
- gt (askem "How old are you? ")
- How old are you? 3
- 3
41C/C Example
- C/C Convert units of sq. meters to sq. yards
- include ltiostream.hgt
- void main ()
-
- const float meters_to_yards 1.196
- float size_in_sqmeters
- float size_in_sqyards
- cout ltlt "Enter size in square meters "
- cin gtgt size_in_sqmeters
-
- size_in_sqyards meters_to_yards
size_in_sqmeters - coutltlt"The size in square yards is "
- ltlt size_in_sqyards ltlt endl
42Equivalent Lisp Example
- Literal Translation
- gt (defun converter ()
- (setf meters_to_yards 1.196)
- (format t "Enter size in square meters ")
- (setf size_in_sqmeters (read))
- (setf size_in_sqyards
- ( meters_to_yards size_in_sqmeters))
- (format t "The size in square yards is
A" - size_in_sqyards)
- )
- CONVERTER
- gt (converter)
- Enter size in square meters 2.0
- The size in square yards is 2.392
- NIL
43Better Lisp Function
- Using a more lisp-like style of programming
- gt (defun converter (sq_meters) ( sq_meters
1.196)) - CONVERTER
- gt (converter 2.0)
- 2.392
- Take advantage of toplevel
- Users enter expressions toplevel prints the
return value - Functional programming
- Avoid variable assignments, side effects
- This course covers the Lisp programming language
- Programming language constructs, built-in
functions - Lisp style, philosophy
44Review
- Lisp List Processing
- Data and Programs represented using Symbolic
Expressions - Atoms, Lists (represented using box analogy or
cons cells) - Interpreter functions (load, help, bye)
- Assigning variables (set, setf)
- List manipulation
- cons, remove, first, rest, append, list
- push, pop
- second, third, , tenth
- T, NIL, Predicates
- If, and, or
- Defun