440 likes | 456 Views
CSCI 2210: Programming in Lisp. Introduction to Lisp. CSCI 2210: Programming in Lisp. Instructor Alok Mehta (mehtaa@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
E N D
CSCI 2210: Programming in Lisp Introduction to Lisp CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
CSCI 2210: Programming in Lisp • Instructor • Alok Mehta (mehtaa@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 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Syllabus CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Assignments/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 11:59:59 pm on the due date • Totalof two grace days are given for late submission • After this, there is a late penalty of 10 points per day CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
What is Lisp? • Stands for LISt Processing • An old, differentprogramming 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 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Examples 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 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Lisp 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 > 1 1 > CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Atoms 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))))) CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Expressions • Expressions • Either atoms or a list • Can represent expressions to be evaluated • Format • (operator arg1 arg2 …) • Zero or more arguments • Example • > (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@cs.rpi.edu))) • (department (Computer Science))) CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Expressions 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) > 1 1 > (sqrt 4.0) 2.0 > (+ 2 3) ; Note that expressions are in prefix notation! 5 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Rules 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: > (/ (* 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 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
More Expression Examples > (/ (* 4 6) 3)8> (+ 1 2 3 4 5) ; The + operator takes zero or more args15> (+)0> "Hello""Hello"> (sqrt (+ 1 3))2.0> (quote (+ 1 3)) ; Exception! Quote = Don't evaluate arg(+ 1 3)> '(+ 1 3) ; shortcut for (quote (+ 1 3))(+ 1 3) CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
The Quote Operator • Special Operator • Disobeys the evaluation rule • Does NOT evaluate its argument > (sqrt (+ 1 3))2.0> (quote (+ 1 3))(+ 1 3)> (quote hello)HELLO> 'helloHELLO> helloError: Attempt to take the value of the unbound variable `HELLO'. [condition type: UNBOUND-VARIABLE] CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Symbols • In the expression below, HELLO is a Symbol • > '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 • > hello • Error: … [condition type: UNBOUND-VARIABLE] • If the symbol HELLO was bound to something, the value would have been returned • > (set (quote hello) 3) ; initialize HELLO to 3 • 3 • > hello • 3 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Set, Setf Assign Variables • Set and Setf assign variables (side effect) • > (set (quote a) '(+ 5 3)) • (+ 5 3) • > (setf b (+ 5 3)) ; equivalent to (set (quote b) (+ 5 3)) • 8 • Examining variables • > a • (+ 5 3) • > b • 8 • Accessing variables • > (+ 3 b) • 11 • > (+ 3 'b) • ** error ** • > (+ 3 a) • ** error ** CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Overview 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 ((3+2)*(7+8)) " Double Quote. Surrounds character strings. • "This is a thirty-nine character string." ’ Single (Forward) Quote. Don’t 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 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
The Story So Far... • Atoms • Lists • Expressions • The Evaluation Rule • Symbols • Set, Setf • Quote (') CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
How 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 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Using Lisp on RCS • Conventions • $ UNIX Prompt • > LISP Interpreter prompt • From a UNIX prompt, start the lisp interpreter • $ gcl • GCL (GNU Common Lisp) Version(2.2) Mon Sep 30 09:45:44 EDT 1996 • Licensed under GNU Public Library License • Contains Enhancements by W. Schelter • > • At the Lisp prompt, type your Lisp Expressions • > (* (+ 3 2) (+ 7 8)) • 75 • > • Lisp expressions return values • Return values can be used in other expressions CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Using Lisp on RCS • Recovering from errors in GCL (:q) • > (+ 4 ’x) • Error: "x" is not of type NUMBER. • Fast links are on: do (si::use-fast-links nil) for debugging • Error signalled by +. • Broken at +. Type :H for Help. • >> :q • Executing lisp commands from a file • > (load "prog1.lsp") • ** Reads and executes the lisp expressions contained in “prog1.lsp” ** • Accessing on-line help • > (help) • Exiting from GCL: “(bye)” or “CTRL-d” • > (bye) CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
How 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 • > (load "hello.lsp") • t • Load returns the result of the LAST expression evaluated in the lisp file CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Constructing New Lists • One way: Use quote operator • > (quote (1 2 3)) • (1 2 3) • > '(1 2 3) • (1 2 3) • Another way: Use the list operator • > (list 1 2 3) • (1 2 3) • When is one better than another? Depends... • > '(1 2 (3 (4)) 5) • (1 2 (3 (4)) 5) • > (list 1 2 (list 3 (list 4)) 5) • (1 2 (3 (4)) 5) • > '(1 2 (+ 3 4) 5) • (1 2 (+ 3 4) 5) • > (list 1 2 (+ 3 4) 5) • (1 2 7 5) CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Cons, Remove, First, Rest • Lists are used to represent knowledge • > (setf complang '(C++ Lisp Java Cobol)) • (C++ LISP JAVA COBOL) • Cons (CONStruct) adds an element to a list • > (setf complang (cons 'Perl complang)) • (PERL C++ LISP JAVA COBOL) • Remove removes an element from a list • > (setf complang (remove 'Cobol complang)) • (PERL C++ LISP JAVA) • First gets the first element of a list • > (first complang) • PERL • Rest gets everything except the first element • > (rest complang) • (C++ LISP JAVA) CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Lists are like boxes; NIL=Empty • Lists are like boxes; they can be nested • ((( A B ) C D ( E ) ( )) ( F ) G H (((I)(J)))) • ‘NIL’ is an empty list • > (setf messy '(((A B) C D (E) ( )) (F) G H (((I)(J)))) ) • (((A B) C D (E) NIL) (F) G H (((I)(J)))) • > (first messy) • ((A B) C D (E) NIL) G H C D F A B E I J CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
First, 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 • > (first '((a) b)) ; returns (A) • > (first '(a b)) ; returns A • > (first '(a)) ; returns A • > (first '( )) ; returns NIL • > (rest '((a) b)) ; returns (B) • > (rest '(a b)) ; returns (B) • > (rest '(a)) ; returns NIL • > (rest '( )) ; returns NIL CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Getting the second element • Use combinations of first and rest • > (setf abcd '(a b c d)) • (A B C D) • > (first (rest abcd)) • B • > (first '(rest abcd)) • REST ; Quote stops expression from being evaluated! • Or, use second • > (second abcd) • B • third, fourth, … , tenth are also defined CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Exercises • Evaluate • > (first '((a b) (c d))) • > (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)))) CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Setf Revisited • Setf • Format • (setf <var1> <value1> <var2> <value2> …) • Example • > (setf x 0 y 0 z 2) • 2 • Returns • the value of the last element • Side effects • assigns values for symbols (or variables) <var1>, <var2>, … • the symbol then becomes an atom that evaluates the value assigned to it • > x • 0 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
List 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 A B alist Cons Cell CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Append, List • Append • Combines the elements of lists • > (append ’(a b c) ’(d e f)) • (A B C D E F) • List • Creates a new list from its arguments • > (list ’a ’b ’(c)) • (A B (C)) A B C D E F CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Cons, Setf; Push; Pop • Cons has no side effects • > (setf complang '(C++ Lisp Java Cobol)) • (C++ LISP JAVA COBOL) • > (cons ’Perl complang) • (PERL C++ LISP JAVA COBOL) • > complang • (C++ LISP JAVA COBOL) • > (setf complang (cons ’Perl complang)) • (PERL C++ LISP JAVA COBOL) • > 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 • > (push complang ’Fortran) • (FORTRAN PERL C++ LISP JAVA COBOL) • > (pop complang) • (PERL C++ LISP JAVA COBOL) CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
T, 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 • > 'nil • NIL • > nil • NIL • The symbol NIL evaluates to itself • > '() • NIL • Functions that determine truth are called predicates CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Predicates: listp • Listp: Is the argument a list? • > (listp 'Hello) • NIL • > (listp '(1 2 3)) • T • > (listp nil) • T • NIL is a list with zero elements, but is still considered a list! • > (listp '()) • T • > (listp '(HELLO)) • T • > (listp (HELLO)) • *Error* • > (listp '(+ 1 2 3)) • T • > (listp (+ 1 2 3)) • NIL CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Predicates: null, not • Null: Is the argument an empty list? • > (null nil) • T • > (null t) • NIL • > (null 3.4) • NIL • > (null '(1 2 3)) • NIL • Not: Returns the opposite of argument • > (not nil) • T • > (not t) • NIL • > (not '(1 2 3)) • NIL • Not and Null are equivalent CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
If • If is a macro • Macros do not follow the Lisp evaluation rule • Syntax: (if <predicate> <then-part> <else-part>) • Evaluates the first argument, <predicate> • 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 (> a b) a b) ; returns maximum of a and b CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
And/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 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Procedure 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)) CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Defun • Defun is a Lisp macro for DEfining FUNctions • (defun <proc-name> • (<parameter1> <parameter2> ...) • <expression1> <expression2> ...) • 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 • > (defun sqr (x) (* x x)) • SQR • > (sqr 5) • 25 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Output • 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 • > (print 3) • 3 • 3 • > (defun verbose-add (a b) • (format t "~A plus ~A equals ~A.~%" a b (+ a b)) • (+ a b)) • > (verbose-add 3 5) • 3 plus 5 equal 8 • 8 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Input • Read • > (defun askem (prompt) • (format t "~A" prompt) • (read)) • ASKEM • > (askem "How old are you? ") • How old are you? 3 • 3 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
C/C++ Example • C/C++: Convert units of sq. meters to sq. yards • #include <iostream.h> • void main () • { • const float meters_to_yards = 1.196; • float size_in_sqmeters; • float size_in_sqyards; • cout << "Enter size in square meters: "; • cin >> size_in_sqmeters; • size_in_sqyards = meters_to_yards * size_in_sqmeters; • cout<<"The size in square yards is " • << size_in_sqyards << endl; • } CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Equivalent Lisp Example • Literal Translation • > (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 • > (converter) • Enter size in square meters: 2.0 • The size in square yards is 2.392 • NIL CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Better Lisp Function • Using a more lisp-like style of programming • > (defun converter (sq_meters) (* sq_meters 1.196)) • CONVERTER • > (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 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta
Review • 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 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta