CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta1 CSCI 2210: Programming in Lisp Introduction to Lisp.

Slides:



Advertisements
Similar presentations
CS 63 LISP Philip Greenspun's Tenth* Rule of Programming:
Advertisements

Lisp. Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks.
C-LISP. LISP 2 Lisp was invented by John McCarthy in 1958 while he was at the Massachusetts Institute of Technology (MIT).John McCarthyMassachusetts Institute.
Lists in Lisp and Scheme a. Lists are Lisp’s fundamental data structures, but there are others – Arrays, characters, strings, etc. – Common Lisp has moved.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
1 Programming Languages and Paradigms Lisp Programming.
Chapter 3 Functional Programming. Outline Introduction to functional programming Scheme: an untyped functional programming language.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Fintan Costello.
CS 355 – PROGRAMMING LANGUAGES Dr. X. Apply-to-all A functional form that takes a single function as a parameter and yields a list of values obtained.
C Programming for engineers Teaching assistant: Ben Sandbank Home page:
Lisp – Introduction יעל נצר מערכות נבונות סמסטר ב' תשס"ו.
Lisp Recitation (cse471/598 Fall 2007 ) Aravind Kalavagattu.
Your First C++ Program Aug 27, /27/08 CS 150 Introduction to Computer Science I C++  Based on the C programming language  One of today’s most.
Lisp. Versions of LISP Lisp is an old language with many variants –LISP is an acronym for List Processing language Lisp is alive and well today Most modern.
First Lecture on Introductory Lisp Yun Peng. Why Lisp? Because it’s the most widely used AI programming language Because AI researchers and theoreticians.
CMSC 471 LISP. Why Lisp? Because it’s the most widely used AI programming language Because it’s good for writing production software (Graham article)
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
TES3111 October 2001 Artificial Intelligence LISP.
CSE S. Tanimoto Introduction 1 LISP Lisp is worth learning for the profound enlightenment experience you will have when you finally get it; that.
Basic Elements of C++ Chapter 2.
COMP 205 – Week 11 Dr. Chunbo Chu. Intro Lisp stands for “LISt Process” Invented by John McCarthy (1958) Simple data structure (atoms and lists) Heavy.
Lisp: a history Developed by John McCarthy in the 1950’s. Developed by John McCarthy in the 1950’s. Only Fortran has higher “seniority” Only Fortran has.
Yu-Tzu Lin ( 林育慈 )
Introduction to C++ - How C++ Evolved Most popular languages currently: COBOL, Fortran, C, C++, Java (script) C was developed in 1970s at AT&T (Richie)
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Basic Lisp CIS 479/579 Bruce R. Maxim UM-Dearborn.
1 Lisp Functions –Built-in functions –Defining functions –Function Evaluation and Special Forms defun, if Control statements –Conditional if, cond –Repetition.
Functional Programming in Scheme
Main Memory Central Processor Unit Keyboard Input Device Secondary Memory Monitor Printer Output Devices.
Common lisp A functional programming language. Useful URL:
CS 330 Programming Languages 11 / 21 / 2006 Instructor: Michael Eckmann.
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
CS 330 Programming Languages 11 / 13 / 2008 Instructor: Michael Eckmann.
Predicates, Functions and Files "I suppose I should learn Lisp, but it seems so foreign." - Paul Graham, Nov 1983.
Programming in Lisp; Instructor: Alok Mehta Programming in Lisp Introduction to Lisp.
LISP Data Types Functional Programming Academic Year Alessandro Cimatti
Introduction to LISP. Lisp Extensible: It lets you define new operators yourself Lisp programs are expressed as lisp data structures –You can write programs.
UMBC CMSC Common Lisp II. UMBC CMSC Input and Output Print is the most primitive output function > (print (list 'foo 'bar)) (FOO BAR) The.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Milos Hauskrecht (PDF) Hieu D. Vu (PPT) LISP PROGARMMING LANGUAGE.
Dr. Philip Cannata 1 Programming Languages Chapter 14 – Functional Programming – Lisp.
Introduction to LISP Atoms, Lists Math. LISP n LISt Processing n Function model –Program = function definition –Give arguments –Returns values n Mathematical.
Computer Eng. Software Lab II , Semester 2, Who I am: Andrew Davison CoE, WiG Lab Office Functional Programming.
1 8/30/06CS150 Introduction to Computer Science 1 Your First C++ Program.
LISP LISt Processing. History & Overview b b One of the oldest high level programming languages. b b First developed in 1958 by John McCarthy. b b Later.
1 Outline Review Introduction to LISP Symbols and Numbers Lists Writing LISP Functions LISPWorks.
CS314 – Section 5 Recitation 9
Functional Programming
Functional Programming Languages
Section 15.4, 15.6 plus other materials
Basic Elements of C++.
CS 326 Programming Languages, Concepts and Implementation
CS 326 Programming Languages, Concepts and Implementation
Getting Started with Lisp
Lists in Lisp and Scheme
Stacks Chapter 4.
LISP A brief overview.
Basic Elements of C++ Chapter 2.
CSE S. Tanimoto Introduction
CSE S. Tanimoto Introduction
Lisp and Scheme I.
LISP A brief overview.
CSE S. Tanimoto Introduction
Summary of what we learned yesterday
Modern Programming Languages Lecture 18 Fakhar Lodhi
Common Lisp II.
Chapter 1 c++ structure C++ Input / Output
Lisp.
LISP primitives on sequences
Presentation transcript:

CSCI Programming in Lisp; Instructor: Alok Mehta1 CSCI 2210: Programming in Lisp Introduction to Lisp

CSCI Programming in Lisp; Instructor: Alok Mehta2 CSCI 2210: Programming in Lisp  Instructor  Alok Mehta –Office Hours: After class or by appointment –Home Phone: (518)  Teaching Assistant  Course Web Page   Textbook  Ansi Common Lisp, by Paul Graham; Prentice Hall 1996

CSCI Programming in Lisp; Instructor: Alok Mehta3 Syllabus

CSCI Programming in Lisp; Instructor: Alok Mehta4 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  Total of two grace days are given for late submission  After this, there is a late penalty of 10 points per day

CSCI Programming in Lisp; Instructor: Alok Mehta5 What 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

CSCI Programming in Lisp; Instructor: Alok Mehta6 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 Programming in Lisp; Instructor: Alok Mehta7 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 Programming in Lisp; Instructor: Alok Mehta8 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 –( ) –(a b (c d) e) –(73 22 b ("A" x) ((((3.14) (4 7) nil (32)))))

CSCI Programming in Lisp; Instructor: Alok Mehta9 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  Can represent data and data structures (course CSCI (name (Programming in Lisp)) (instructor (name (Alok Mehta)) ( (department (Computer Science)))

CSCI Programming in Lisp; Instructor: Alok Mehta10 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 Programming in Lisp; Instructor: Alok Mehta11 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 Programming in Lisp; Instructor: Alok Mehta12 More Expression Examples > (/ (* 4 6) 3) 8 > ( ) ; The + operator takes zero or more args 15 > (+) 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 Programming in Lisp; Instructor: Alok Mehta13 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 > 'hello HELLO > hello Error: Attempt to take the value of the unbound variable `HELLO'. [condition type: UNBOUND-VARIABLE]

CSCI Programming in Lisp; Instructor: Alok Mehta14 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 Programming in Lisp; Instructor: Alok Mehta15 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 Programming in Lisp; Instructor: Alok Mehta16 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 Programming in Lisp; Instructor: Alok Mehta17 The Story So Far...  Atoms  Lists  Expressions  The Evaluation Rule  Symbols  Set, Setf  Quote (')

CSCI Programming in Lisp; Instructor: Alok Mehta18 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  Select Allegro CL Lite for Windows

CSCI Programming in Lisp; Instructor: Alok Mehta19 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 Programming in Lisp; Instructor: Alok Mehta20 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 Programming in Lisp; Instructor: Alok Mehta21 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 Programming in Lisp; Instructor: Alok Mehta22 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) ( )

CSCI Programming in Lisp; Instructor: Alok Mehta23 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 Programming in Lisp; Instructor: Alok Mehta24 Lists are like boxes; NIL=Empty G H C D A B F IJ  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) E

CSCI Programming in Lisp; Instructor: Alok Mehta25 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 Programming in Lisp; Instructor: Alok Mehta26 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 Programming in Lisp; Instructor: Alok Mehta27 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 Programming in Lisp; Instructor: Alok Mehta28 Setf Revisited  Setf  Format (setf …)  Example > (setf x 0 y 0 z 2) 2  Returns –the value of the last element  Side effects –assigns values for symbols (or variables),, … –the symbol then becomes an atom that evaluates the value assigned to it > x 0

CSCI Programming in Lisp; Instructor: Alok Mehta29 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 B C A alist Contents of Address Register (CAR) = Old name for “First” Contents of Decrement portion of Register (CDR) = Old name for “Rest” Cons Cell

CSCI Programming in Lisp; Instructor: Alok Mehta30 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)) ABCDEF

CSCI Programming in Lisp; Instructor: Alok Mehta31 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 Programming in Lisp; Instructor: Alok Mehta32 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 Programming in Lisp; Instructor: Alok Mehta33 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 '( )) T > (listp ( )) NIL

CSCI Programming in Lisp; Instructor: Alok Mehta34 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 Programming in Lisp; Instructor: Alok Mehta35 If  If is a macro  Macros do not follow the Lisp evaluation rule  Syntax: (if )  Evaluates the first argument,  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 Programming in Lisp; Instructor: Alok Mehta36 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 Programming in Lisp; Instructor: Alok Mehta37 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 Programming in Lisp; Instructor: Alok Mehta38 Defun  Defun is a Lisp macro for DEfining FUNctions (defun (...)...)  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 Programming in Lisp; Instructor: Alok Mehta39 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 > (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 Programming in Lisp; Instructor: Alok Mehta40 Input  Read > (defun askem (prompt) (format t "~A" prompt) (read)) ASKEM > (askem "How old are you? ") How old are you? 3 3

CSCI Programming in Lisp; Instructor: Alok Mehta41 C/C++ Example  C/C++: Convert units of sq. meters to sq. yards #include 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 Programming in Lisp; Instructor: Alok Mehta42 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 NIL

CSCI Programming in Lisp; Instructor: Alok Mehta43 Better Lisp Function  Using a more lisp-like style of programming > (defun converter (sq_meters) (* sq_meters 1.196)) CONVERTER > (converter 2.0)  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 Programming in Lisp; Instructor: Alok Mehta44 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