Common Lisp II.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Scheme in Scheme. Why implement Scheme in Scheme  Implementing a language is a good way to learn more about programming languages  Interpreters are.
1 Programming Languages and Paradigms Lisp Programming.
Lambda Calculus and Lisp PZ03J. Lambda Calculus The lambda calculus is a model for functional programming like Turing machines are models for imperative.
Chapter 3 Functional Programming. Outline Introduction to functional programming Scheme: an untyped functional programming language.
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.
A problem with functions: arguments must always have values that can be worked out Whenever we call a function we give it arguments. Lisp then works out.
1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.
Lisp Recitation (cse471/598 Fall 2007 ) Aravind Kalavagattu.
Introduction to Artificial Intelligence Lisp Ruth Bergman Fall 2002.
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.
CSE S. Tanimoto Explicit Function Application 1 Explicit Application of Functions, Functional Arguments and Explicit Evaluation Implicit and explicit.
Symbolic Expressions (S Expressions) Syntax: Opening and Closing parenthesis having elements in between. List represented in LISP: (A B2 C3 Shahid) (A.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
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 1.5 and beyond A very quick tour. Data Atoms (symbols) including numbers – All types of numbers including Roman! (well, in the early days) – Syntactically.
F UNCTIONAL P ROGRAMMING 05 Functions. F UNCTIONS - G LOBAL F UNCTIONS fboundp Tells whether there is a function with a given symbol as its name > (fboundp.
Allegro CL Certification Program Lisp Programming Series Level I Session Top Ten Things to Know.
Yu-Tzu Lin ( 林育慈 )
The Case primitive: matches the evaluated key form against the unevaluated keys by using eql The general format of case is the following: (case (... ).....
PRACTICAL COMMON LISP Peter Seibel 1.
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 and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
CSE 341, S. Tanimoto Lisp Defining Functions with DEFUN Functions are the primary abstraction mechanism available in Lisp. (Others are structures.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
04 Control. Control-Blocks Common Lisp has 3 basic operators for creating blocks of code progn block tagbody If ordinary function calls are the leaves.
Functional Programming in Scheme and 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.
PRACTICAL COMMON LISP Peter Seibel 1.
Operating on Lists Chapter 6. Firsts and Seconds n Transforming list of pairs into two lists –(firsts ‘((1 5) (2 6) (3 7)))  (1 2 3) –(seconds ‘((1 5)
Milos Hauskrecht (PDF) Hieu D. Vu (PPT) LISP PROGARMMING LANGUAGE.
1 Variable Declarations Global and special variables – (defvar …) – (defparameter …) – (defconstant …) – (setq var2 (list 4 5)) – (setf …) Local variables.
Basic Introduction to Lisp
Functional Programming: Lisp MacLennan Chapter 10.
CSE 341, S. Tanimoto Lisp Explicit Application of Functions and Functional Arguments In Lisp, functions can be passed as arguments to other functions.
1 Outline Review Introduction to LISP Symbols and Numbers Lists Writing LISP Functions LISPWorks.
Artificial Intelligence and Lisp Lecture 6 LiU Course TDDC65 Autumn Semester,
Section 15.4, 15.6 plus other materials
Edited by Original material by Eric Grimson
Defining Macros in Lisp
CS 326 Programming Languages, Concepts and Implementation
Modern Programming Languages Lecture 20 Fakhar Lodhi
Getting Started with Lisp
LISP A brief overview.
First Lecture on Introductory Lisp
FP Foundations, Scheme In Text: Chapter 14.
Modern Programming Languages Lecture 21 Fakhar Lodhi
Modern Programming Languages Lecture 20 Fakhar Lodhi
The Metacircular Evaluator (Continued)
CSE S. Tanimoto Explicit Function Application
6.001 SICP Further Variations on a Scheme
Explicit Application of Procedures, and Explicit Evaluation
Lisp: Using Functions as Data
LISP A brief overview.
6.001 SICP Variations on a Scheme
Defining Functions with DEFUN
Peter Seibel Practical Common Lisp Peter Seibel
Abstraction and Repetition
Functional Programming: Lisp
Lisp: Using Functions as Data
Modern Programming Languages Lecture 18 Fakhar Lodhi
Lisp.
More Scheme CS 331.
The general format of case is the following: (case <key form>
LISP primitives on sequences
Procedures with optional parameters which do not require matching arguments Example: consider the exponent function which may take one argument, m, in.
Presentation transcript:

Common Lisp II

Input and Output Print is the most primitive output function > (print (list 'foo 'bar)) (FOO BAR) The most general output function in CL is format which takes two or more arguments: the first indicates where the input is to be printed, the second is a string template, the remaining arguments are objects whose printed representations are to be inserted into the template: > (format t “~A plus ~A equals ~A.~%” 2 3 (+ 2 3)) 2 plus 3 equals 5. NIL

Read The standard function for input is read. When given no arguments, it reads from the default place, which is usually standard input. > (defun ask (string) (format t “~A” string) (read)) ask > (ask “How old are you? “) How old are you? 29 29

Local Variables One of the most frequently used operators in CL is let. This allows local variables to be used in a function. A let expression has two parts. First comes a list of instructions for creating variables, each of the form var or (var expression). Local variables are valid within the body of the let. After the list of variables and values comes the body of expressions, which are evaluated in order. > (let ((x 100) (y 200)) (print (+ x y)) (setq x 200) ‘foo) 300 400 foo

A let example > (ask-number) Please enter a number. number > (defun ask-number () (format t “Please enter a number. “) (let ((val (read))) (if (numberp val) val (ask-number)))) ASK-NUMBER > (ask-number) Please enter a number. number Please enter a number. (this is a number) Please enter a number. 52 52

Global variables Global variables are visible throughout the program. Global variables can be created by giving a symbol and a value to defparameter or defvar. > (defparameter *foo* 1) *FOO* > *foo* 1 > (defvar *bar* (+ *foo* 1)) *BAR* > *bar* 2 > (defvar *bar* 33) Note: (defparameter v e) creates a global variable named v and sets its value to be e. (defvar v e) is just like defparameter if no global variable named v exists. Otherwise it does nothing.

Global constants You can define a global constant, by calling defconstant. > (defconstant +limit+ 100) +LIMIT+ > (setf +limit+ 99) *** - SETQ: the value of the constant +LIMIT+ may not be altered 1. Break [5]> The plus-something-plus is a lisp convention to identify symbols as constants. Just like star-something-star is a lisp convention to identify global variables.

When in doubt When in doubt about whether some symbol is a global variable or constant, use boundp. > (boundp ‘*foo*) T > (boundp ‘fishcake) NIL

Assignment There are several assignment operators in Common Lisp: set, setq and setf the most general assignment operator is setf. We can use it to assign both local and global variables: > (setf *blob* 89) 89 > (let ((n 10)) (setf n 2) n) 2

Setf You can create global variables implicitly just by assigning them values. > (setf x (list ‘a ‘b ‘c)) (A B C) However, it is better lisp style to use defparameter to declare global variables. You can give setf any even number of arguments: (setf a 1 b 2 c 3) is the same as: (setf a 1) (setf b 2) (setf c 3)

You can do more than just assign values to variables with setf. The first argument to setf can be an expression as well as a variable name. In such cases, the value of the second argument is inserted in the place referred to by the first: > (setf (car x) ‘n) N > (N B C)

Setf > (setq a (make-array 3)) #(NIL NIL NIL) > (aref a 1) NIL > (setf (aref a 1) 3) 3 > a #(NIL 3 NIL) > (defstruct foo bar) FOO > (setq a (make-foo)) #s(FOO :BAR NIL) > (foo-bar a) NIL > (setf (foo-bar a) 3) 3 > a #s(FOO :BAR 3)

Functional programming Functional programming means writing programs that work by returning values, instead of by modifying things. It is the dominant programming paradigm in Lisp. Must built-in lisp functions are meant to be called for the values they return, not for side-effects.

Examples of functional programming The function remove takes an object and a list and returns a new list containing everything but that object: > (setf lst ‘(b u t t e r)) (B U T T E R) > (remove ‘e lst) (B U T T R) Note: remove does not remove an item from the list! The original list is untouched after the call to remove: > lst To actually remove an item from a list you would have to use setf: > (setf lst (remove ‘e lst)) Functional programming means, essentially, avoiding setf, and other assignment macros.

How remove could be defined Here’s how remove could be defined: (defun remove (x list) (cond ((null list) nil) ((equal x (car list)) (remove x (cdr list))) (t (cons (car list) (remove x (cdr list)))))) Note that it “copies” the top-level of the list.

Iteration When we want to do something repeatedly, it is sometimes more natural to use iteration than recursion. This function uses do to print out the squares of the integers from start to end: (defun show-squares (start end) (do ((i start (+ i 1))) ((> i end) ‘done) (format t “~A ~A~%” i (* i i))))

do The do macro is CL’s fundamental iteration operator. Like let, do can create variables, and the first argument is a list of variable specifications. Each element is of the form: (var initial update) where variable is a symbol, and initial and update are expressions. The second argument to do should be a list containing one or more expressions. The first expression is used to test whether iteration should stop. In the case above, the test expression is (> i end). The remaining expression in this list will be evaluated in order when iteration stops, and the value of the last will be returned as the value of the do, done in this example. The remaining arguments to do comprise the body of the loop.

Dolist CL has a simpler iteration operator for handling lists, dolist. (defun len (lst) “I calculate the length of lst” (let ((l 0)) (dolist (obj lst) (setf l (+ l 1))) l)) Here dolist takes an argument of the form (variable expression), followed by a body of expressions. The body will be evaluated with variable bound to successive elements of the list returned by expression.

eval You can call Lisp’s evaluation process with the eval function. > (setf s1 '(cadr '(one two three))) (CADR '(ONE TWO THREE)) > (eval s1) TWO > (eval (list 'cdr (car '((quote (a . b)) c)))) B

Functions as objects In lisp, functions are regular objects, like symbols, or strings, or lists. If we give the name of a function to function, it will return the associated object. Like quote, function is a special operator, so we don’t have to quote the argument: > (defun add1 (n) (+ n 1)) ADD1 > (function +) #<SYSTEM-FUNCTION +> > (function add1) #<CLOSURE ADD1 (N) (DECLARE (SYSTEM::IN-DEFUN ADD1)) (BLOCK ADD1 (+ N 1))>

This abbreviation is known as sharp-quote. Just as we can use ‘ as an abbreviation for quote, we can use #’ as an abbreviation for function: > #’+ #<SYSTEM-FUNCTION +> This abbreviation is known as sharp-quote. Like any other kind of object, we can pass functions as arguments. One function that takes a function as an argument is apply.

Apply A simple version of apply could be written as follows Apply takes a function and a list of arguments for it, and returns the result of applying the function to the arguments: > (apply #’+ ‘(1 2 3)) 6 It can be given any number of arguments, so long as the last is a list: > (apply #’+ 1 2 ‘(3 4 5)) 15 A simple version of apply could be written as follows (defun apply (f list) (eval (cons f list)))

Funcall The function funcall is like apply but does not need the arguments to be packaged in a list: > (funcall #’+ 1 2 3) 6 It could be written as: (defun funcall (f &rest args) (eval (cons f args)))

Lambda The defun macro creates a function and gives it a name. However, functions don’t have to have names, and we don’t need defun to define them. We can refer to functions literally by using a lambda expression.

Lambda expression A lambda expression is a list containing the symbol lambda, followed by a list of parameters, followed by a body of zero or more expressions: > (setf f (lambda (x) (+ x 1))) #<CLOSURE :LAMBDA (X) (+ X 1)> > (funcall f 100) 101

A lambda expression can be considered as the name of a function. Like an ordinary function name, a lambda expression can be the first element of a function call: > ((lambda (x) (+ x 100)) 1) 101 and by affixing a sharp-quote to a lambda expression, we get the corresponding function: > (funcall #’(lambda (x) (+ x 100)) 1)

Types In CL values have types, not variables. You don’t have to declare the types of variables, because any variable can hold objects of any type. Though type declaration is never required, you may want to make them for reasons of efficiency. The built-in CL types form a hierarchy of subtypes and supertypes. The type t is the supertype of all types, so everything is of type t.

> (typep 27 ‘t) T > (typep 27 ‘atom) > (typep 27 ‘number) > (typep 27 ‘real) > (typep 27 ‘rational) > (typep 27 ‘integer) > (typep 27 ‘fixnum) > (typep 27 ‘vector) NIL t atom number real rational integer fixnum 27