1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D....

74
1 COSC3306: COSC3306: Programming Programming Paradigms Paradigms Lecture 11: Lecture 11: Applicative Applicative Programming with Lisp Programming with Lisp Haibin Zhu, Ph.D. Haibin Zhu, Ph.D. Computer Science Computer Science Nipissing University Nipissing University (C) 2003 (C) 2003

Transcript of 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D....

Page 1: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

11

COSC3306:COSC3306:Programming ParadigmsProgramming Paradigms

Lecture 11: ApplicativeLecture 11: ApplicativeProgramming with LispProgramming with Lisp

Haibin Zhu, Ph.D.Haibin Zhu, Ph.D.Computer ScienceComputer ScienceNipissing University Nipissing University

(C) 2003(C) 2003

Page 2: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

22

Versions of LISPVersions of LISP

LispLisp is an old language with many is an old language with many variantsvariants

Lisp is alive and well todayLisp is alive and well today

Most modern versions are based on Most modern versions are based on Common LispCommon Lisp

LispWorks LispWorks is based on Common Lispis based on Common Lisp

SchemeScheme is one of the major variants is one of the major variants

The essentials haven’t changed muchThe essentials haven’t changed much

Page 3: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

33

RecursionRecursion

Recursion is essential in LispRecursion is essential in Lisp

A A recursive definitionrecursive definition is a definition in is a definition in whichwhich– certain things are specified as belonging to certain things are specified as belonging to

the category being defined, andthe category being defined, and– a rule or rules are given for building new a rule or rules are given for building new

things in the category from other things things in the category from other things already known to be in the category.already known to be in the category.

Page 4: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

44

Informal SyntaxInformal Syntax

An An atomatom is either an integer or an is either an integer or an identifier.identifier.

A A listlist is a left parenthesis, followed by zero is a left parenthesis, followed by zero or more S-expressions, followed by a right or more S-expressions, followed by a right parenthesis.parenthesis.

An An S-expressionS-expression is an atom or a list. is an atom or a list.

Example: Example: (A (B 3) (C) ( ( ) ) )(A (B 3) (C) ( ( ) ) )

Page 5: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

55

Formal Syntax (approximate)Formal Syntax (approximate)

<S-expression> ::= <atom> | <list><S-expression> ::= <atom> | <list>

<atom> ::= <number> | <identifier><atom> ::= <number> | <identifier>

<list> ::= ( <S-expressions> )<list> ::= ( <S-expressions> )

<S-expressions > ::= <empty><S-expressions > ::= <empty> | <S-expressions > <S-expression> | <S-expressions > <S-expression>

<number> ::= <digit> | <number> <number> ::= <digit> | <number> <digit><digit>

<identifier> ::= <identifier> ::= string of printable characters, string of printable characters, not including parenthesesnot including parentheses

Page 6: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

66

LISP facilitiesLISP facilities

LISP facilities:LISP facilities:– A method for storing data,A method for storing data,– A set of built-in functions,A set of built-in functions,– A set of functional forms, andA set of functional forms, and– A set of operators.A set of operators.

Two featuresTwo features– Each data object carries a run-time descriptor giving Each data object carries a run-time descriptor giving

its type and other attributes.its type and other attributes.– If a data object has components (is a structured data If a data object has components (is a structured data

object), the components are never represented object), the components are never represented directly as part of the data object; instead a pointer to directly as part of the data object; instead a pointer to the component data object is used. the component data object is used.

Page 7: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

77

Data ObjectsData Objects

Every LISP data object, whether a Every LISP data object, whether a program or data, is either an program or data, is either an atomatom or a or a conscons. An atom is an object that is . An atom is an object that is indivisible in nature and takes two forms:indivisible in nature and takes two forms:– A literal atom (symbol), which is a string A literal atom (symbol), which is a string

beginning with a letter, andbeginning with a letter, and– A numeric atom (number), which is a number A numeric atom (number), which is a number

used for integer and real arithmetic used for integer and real arithmetic operations; numbers are their own values. operations; numbers are their own values.

Page 8: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

88

T and NILT and NIL

NILNIL is the name of the empty list is the name of the empty list

As a test, As a test, NILNIL means “false” means “false”

T T is usually used to mean “true,” but…is usually used to mean “true,” but…

……anything that isn’tanything that isn’t NIL NIL is “true” is “true”

NIL NIL is both an atom and a listis both an atom and a list– it’s defined this way, so just accept itit’s defined this way, so just accept it

Page 9: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

99

Function calls and dataFunction calls and data

A function call is written as a listA function call is written as a list– the first element is the name of the functionthe first element is the name of the function– remaining elements are the argumentsremaining elements are the arguments

Example: Example: (F A B)(F A B)– calls function calls function FF with arguments with arguments AA and and BB

Data is written as atoms or listsData is written as atoms or lists

Example: Example: (F A B)(F A B) is a list of three elements is a list of three elements– Do you see a problem here?Do you see a problem here?

Page 10: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1010

QuotingQuoting

Is Is (F A B)(F A B) a call to a call to FF, or is it just data?, or is it just data?

All All literal dataliteral data must be quoted (atoms, too) must be quoted (atoms, too)

(QUOTE (F A B))(QUOTE (F A B)) is the list is the list (F A B)(F A B)– QUOTEQUOTE is a “special form” is a “special form”– The arguments to a special form are not The arguments to a special form are not

evaluatedevaluated

'(F A B)'(F A B) is another way to quote data is another way to quote data– There is just one single quote at the beginningThere is just one single quote at the beginning– It quotes one S-expressionIt quotes one S-expression

Page 11: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1111

Basic FunctionsBasic Functions

CARCAR returns the head of a list returns the head of a list

CDR CDR returns the tail of a listreturns the tail of a list

CONS CONS inserts a new head into a listinserts a new head into a list

EQ EQ compares two atoms for equalitycompares two atoms for equality

ATOM ATOM tests if its argument is an atomtests if its argument is an atom

Page 12: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1212

Figure 13.1 Memory representation of (cons ‘A ‘B)

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 13: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1313

Figure 13.2 Memory representation of (cons ‘A (cons ‘CAR ‘NIL))

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 14: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1414

Figure 13.3 Memory representation of (cons ‘A (cons ‘B ‘C))

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 15: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1515

Figure 13.4 A representation of list (A (BC) D)

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 16: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1616

Figure 13.5 A representation of list ((AB) (C ) (DF))

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 17: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1717

Figure 13.6 Cell diagram representation of list (a b c)

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 18: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1818

Figure 13.7 Cell diagram representation of list (a b) (c ) (d f))

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 19: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1919

Figure 13.9 Scheme evaluation of expression ( * ( - 5 2) (+ 2 3))

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 20: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2020

Other useful FunctionsOther useful Functions

(NULL S) (NULL S) tests if tests if SS is the empty list is the empty list

(LISTP S) (LISTP S) tests if tests if SS is a list is a list

LIST LIST makes a list of its (evaluated) makes a list of its (evaluated) argumentsarguments– (LIST 'A '(B C) 'D)(LIST 'A '(B C) 'D) returns returns (A (B C) D)(A (B C) D)– (LIST (CDR '(A B)) 'C) (LIST (CDR '(A B)) 'C) returnsreturns ((B) C) ((B) C)

APPEND APPEND concatenates two listsconcatenates two lists– (APPEND '(A B) '((X) Y) )(APPEND '(A B) '((X) Y) ) returns returns (A B (X) Y)(A B (X) Y)

Page 21: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2121

CARCAR

The The CARCAR of a list is the first thing in the list of a list is the first thing in the list

CARCAR is only defined for is only defined for nonemptynonempty lists lists

If L is Then (CAR L) is

(A B C) A( (X Y) Z) (X Y)

( ( ) ( ) ) ( )

( ) undefined

Page 22: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2222

CDRCDR

The The CDRCDR of a list is what's left when you remove the of a list is what's left when you remove the CARCAR

CDRCDR is only defined for is only defined for nonemptynonempty lists lists

The The CDRCDR of a list is always a list of a list is always a list

Page 23: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2323

CDR CDR examplesexamples

If L is Then (CDR L) is

(A B C) (B C)( (X Y) Z) (Z)

( ( ) ( ) ) ( ( ) )

( ) undefined

(X) ( )

Page 24: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2424

CONSCONSCONSCONS takes two arguments takes two arguments– The first argument can be any S-expressionThe first argument can be any S-expression– The second argument should be a listThe second argument should be a list

The result is a new list whose The result is a new list whose CARCAR is the first is the first argument and whose argument and whose CDRCDR is the second is the second

Just move one parenthesis to get the result:Just move one parenthesis to get the result:

CONS of A ( B C ) gives ( A B C )

Page 25: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2525

CONS CONS examplesexamples

L (CAR L) (CDR L) (CONS (CAR L) (CDR L))

(A B C) A (B C) (A B C)( (X Y) Z) (X Y) (Z) ( (X Y) Z)

( ( ) ( ) ) ( ) ( ( ) ) ( ( ) ( ) )

( ) undefined undefined undefined

(X) X ( ) (X)

CONSCONS puts together what puts together what CARCAR and and CDRCDR take aparttake apart

Page 26: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2626

Dotted PairsDotted Pairs

The second argument to The second argument to CONSCONS should be should be a lista list

If it isn't, you get a If it isn't, you get a dotted pairdotted pair

CONSCONS of of AA and and BB is is (A . B)(A . B)

If you get a dotted pair, it's because you If you get a dotted pair, it's because you gave gave CONS CONS an atom as a second an atom as a second argumentargument

Page 27: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2727

EQEQ

EQEQ tests whether two atoms are equal tests whether two atoms are equal– Integers are a kind of atomIntegers are a kind of atom

EQEQ is undefined for lists is undefined for lists– it might work for lists, it might notit might work for lists, it might not– but it won't give you an error messagebut it won't give you an error message

As with any predicate, As with any predicate, EQEQ returns either returns either NILNIL or something that isn't or something that isn't NILNIL

Page 28: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2828

ATOMATOM

ATOMATOM takes any S-expression as an takes any S-expression as an argumentargument

ATOMATOM returns "true" if the argument you returns "true" if the argument you gave it is an atomgave it is an atom

As with any predicate, As with any predicate, ATOMATOM returns returns either either NILNIL or something that isn't or something that isn't NILNIL

Page 29: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2929

CONDCOND

COND COND implements the implements the if...then...elseif...then...elseif...then... if...then...elseif...then...elseif...then... control structurecontrol structure

The arguments to a function are evaluated The arguments to a function are evaluated before the function is calledbefore the function is called– This isn't what you want forThis isn't what you want for COND COND

COND COND is a is a special formspecial form

Page 30: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3030

To be continuedTo be continued

COND COND

MemberMember

EqualEqual

Page 31: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3131

Special formsSpecial forms

A A special formspecial form is like a function, but it is like a function, but it evaluates the arguments as it needs themevaluates the arguments as it needs them

CONDCOND, , QUOTEQUOTE and and DEFUNDEFUN are special are special formsforms

You can define your own special formsYou can define your own special forms

Page 32: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3232

Form of theForm of the COND COND

(COND (condition1 result1 ) (condition2 result2 ) . . . (T resultN ) )

Page 33: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3333

Defining FunctionsDefining Functions

(DEFUN (DEFUN function_name function_name parameter_listparameter_list function_body function_body ) )

Example: Test if the argument is the empty Example: Test if the argument is the empty listlist

(DEFUN NULL (X)(DEFUN NULL (X) (COND (COND (X NIL) (X NIL) (T T) ) ) (T T) ) )

Page 34: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3434

Example: MEMBERExample: MEMBER

As an example we defineAs an example we define MEMBER MEMBER, which tests , which tests whether an atom is in a list of atomswhether an atom is in a list of atoms

(DEFUN MEMBER (A LAT)(DEFUN MEMBER (A LAT) (COND (COND ((NULL LAT) NIL) ((NULL LAT) NIL) ((EQ A (CAR LAT)) T) ((EQ A (CAR LAT)) T) (T (MEMBER A (CDR LAT))) ) ) (T (MEMBER A (CDR LAT))) ) )

MEMBERMEMBER is typically a built-in function is typically a built-in function

Page 35: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3535

Rules for RecursionRules for Recursion

Handle the base (“simplest”) cases firstHandle the base (“simplest”) cases first

Recur only with a “simpler” caseRecur only with a “simpler” case– ““Simpler” = more like the base caseSimpler” = more like the base case

Don’t alter global variables (you can’t Don’t alter global variables (you can’t anyway with the Lisp functions I’ve told anyway with the Lisp functions I’ve told you about)you about)

Don’t look down into the recursionDon’t look down into the recursion

Page 36: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3636

Guidelines for Lisp FunctionsGuidelines for Lisp Functions

Unless the function is trivial, start with Unless the function is trivial, start with CONDCOND..

Handle the base case first.Handle the base case first.

Avoid having more than one base case.Avoid having more than one base case.

The base case is usually testing for The base case is usually testing for NULLNULL..

Do something with the Do something with the CARCAR and recur with and recur with the the CDRCDR..

Page 37: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3737

Example: UNIONExample: UNION

(DEFUN UNION (SET1 SET2) (COND ((NULL SET1) SET2) ((MEMBER (CAR SET1) SET2) (UNION (CDR SET1) SET2) ) (T (CONS (CAR SET1) (UNION (CDR SET1) SET2) )) ) )

Page 38: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3838

Still more useful FunctionsStill more useful Functions

(LENGTH L) (LENGTH L) returns the length of list returns the length of list LL

(RANDOM N)(RANDOM N) , where , where N N is an integer, is an integer, returns a random integer returns a random integer >= 0>= 0 and and < N< N. .

Page 39: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3939

How EQUAL could be definedHow EQUAL could be defined

(defun equal (x y)(defun equal (x y) ; this is how equal could be defined; this is how equal could be defined (cond ((numberp x) (= x y))(cond ((numberp x) (= x y)) ((atom x) (eq x y))((atom x) (eq x y)) ((atom y) nil)((atom y) nil) ((equal (car x) (car y))((equal (car x) (car y)) (equal (cdr x) (cdr y))))) (equal (cdr x) (cdr y)))))

Page 40: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4040

Lambda expressionLambda expressionA lambda expression has the form:A lambda expression has the form:

(lambda(lambda argument-listargument-listfunction-bodyfunction-body ) )

In other words, a lambda expression is somewhat like In other words, a lambda expression is somewhat like defundefun, except that it defines an unnamed function, or it , except that it defines an unnamed function, or it allows the user to define a function with no name.allows the user to define a function with no name.For example,For example,

((lambda((lambda (x y) (+ x y)) 2 3)(x y) (+ x y)) 2 3)binds x and y to 2 and 3, respectively, and applies +, giving binds x and y to 2 and 3, respectively, and applies +, giving 5 as the returned value of this definition. Even though LISP 5 as the returned value of this definition. Even though LISP can be used as a functional programming language, few can be used as a functional programming language, few applications written in LISP are purely applicative. Any applications written in LISP are purely applicative. Any realistic LISP program makes heavy use of non-applicative realistic LISP program makes heavy use of non-applicative features to achieve a reasonable level of efficiency. features to achieve a reasonable level of efficiency.

Page 41: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4141

The The setset function function

The The setset function is simply an assignment statement and a value of a function is simply an assignment statement and a value of a symbol can be assigned with the general formsymbol can be assigned with the general form

(set(set symbolsymbol expression)expression)in which the in which the expressionexpression is assigned to is assigned to symbolsymbol and and symbolsymbol evaluates evaluates to that value until to that value until setset is applied again. Examine the following is applied again. Examine the following examples about examples about setset function. function.evaleval (set ‘X ‘(A B C) ) (set ‘X ‘(A B C) )(A B C)(A B C)evaleval (set ‘B ‘3) (set ‘B ‘3)33evaleval(set ‘Y ‘A)(set ‘Y ‘A)AAevaleval Y YAAevaleval (set ‘Z X) (set ‘Z X)(A B C)(A B C)

Page 42: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4242

The special form letThe special form letThe special form The special form letlet is a function that provides a way of introducing is a function that provides a way of introducing temporary variables or binding local variables. Temporary variables can temporary variables or binding local variables. Temporary variables can serve the result of a computation. The general form of serve the result of a computation. The general form of letlet is is

(let(let ( (variable1( (variable1 value1)value1) (variable2(variable2 value2)value2)

…… (variablen(variablen valuen) )valuen) )body)body)

in which variable1, variable2, … , variablein which variable1, variable2, … , variablenn, are symbols (, are symbols (letlet does not does not evaluate them) that will be used as names on introduced variables. They evaluate them) that will be used as names on introduced variables. They can be referred to by any code that appears in the can be referred to by any code that appears in the bodybody form. When form. When letlet is invoked, each of value1, value2, …, valueis invoked, each of value1, value2, …, valuenn is evaluated in turn. When is evaluated in turn. When they all have been evaluated, the new variables are given their values. they all have been evaluated, the new variables are given their values. Examine the following examples about Examine the following examples about letlet function. function.evaleval (let ((A 3)) (cons A (let ((A 4)) A) ) ) (let ((A 3)) (cons A (let ((A 4)) A) ) )(3 4)(3 4)evaleval (let ((A 3)) (let ((A 4) (B A) ) (cons A B) ) ) (let ((A 3)) (let ((A 4) (B A) ) (cons A B) ) )(4 3)(4 3)

Page 43: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4343

The special form prog The special form prog

(progn expression1, expression2, …, (progn expression1, expression2, …, expressionn)expressionn)

(progn (set ‘x 3) (set ‘y 4) (print (* x y)))(progn (set ‘x 3) (set ‘y 4) (print (* x y)))

Page 44: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4444

Some simple list processing examplesSome simple list processing examples

(defun member (x l)(defun member (x l) (cond ((atom l) nil)(cond ((atom l) nil) ((equal x (car l)) (cdr l))((equal x (car l)) (cdr l)) (T (member x (cdr l))))(T (member x (cdr l))))

(defun append (l1 l2)(defun append (l1 l2) (if (null l1) (if (null l1) l2 l2 (cons (car l1) (append (cdr l1) l2))))(cons (car l1) (append (cdr l1) l2))))

Page 45: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4545

Variations on reverseVariations on reverse

;; either of these does O(n^2) cons operations;; either of these does O(n^2) cons operations

(defun reverse (l)(defun reverse (l)

(if (null l)(if (null l)

nilnil

(append (reverse (cdr l)) (list (car l))))) (append (reverse (cdr l)) (list (car l)))))

(defun reverse (l) (defun reverse (l)

(and l (append (reverse (cdr l)) (list (car l))))) (and l (append (reverse (cdr l)) (list (car l)))))

Page 46: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4646

FlattenFlatten

(defun flatten (l)(defun flatten (l)

(cond ((null l) nil) ; empty list do nothing(cond ((null l) nil) ; empty list do nothing

((atom (car l)) ((atom (car l))

; cons an atom onto flattend cdr; cons an atom onto flattend cdr

(cons (car l) (flatten (cdr l))))(cons (car l) (flatten (cdr l))))

; otherwise flatten head & tail and append results; otherwise flatten head & tail and append results

(t (append (flatten (car l)) (flatten (cdr l))))))(t (append (flatten (car l)) (flatten (cdr l))))))

Page 47: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4747

Higher order functionsHigher order functions

(defun mapcar (f l)(defun mapcar (f l)

(if (null l) (if (null l)

nil nil

(cons (apply f (list (car l)))(cons (apply f (list (car l)))

(mapcar f (cdr l)))))(mapcar f (cdr l)))))

Page 48: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4848

ExamplesExamples

http://sandbox.mc.edu/~bennet/cs404/doc/http://sandbox.mc.edu/~bennet/cs404/doc/lisp.htmllisp.html

http://www.cs.ualberta.ca/~tommy/ta/325/lihttp://www.cs.ualberta.ca/~tommy/ta/325/lisp_examples.htmlsp_examples.html

http://www.notam02.no/internt/cm-sys/cm-http://www.notam02.no/internt/cm-sys/cm-1.4/doc/examples/1.4/doc/examples/

Page 49: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4949

Common LispCommon Lisp

Page 50: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5050

Why Common Lisp?Why Common Lisp?

Common Lisp is a high-level, dynamical, Common Lisp is a high-level, dynamical, extensible language, suitable for symbolic extensible language, suitable for symbolic and numerical processing; and numerical processing; Modern Common Lisp implementations Modern Common Lisp implementations provide compilers, automatic memory provide compilers, automatic memory management, multithreading, powerful management, multithreading, powerful debuggers; debuggers; A large number of legacy AI systems A large number of legacy AI systems written in Lisp exist. written in Lisp exist.

Page 51: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5151

Input and OutputInput and OutputPrint is the most primitive output functionPrint is the most primitive output function> (print (list 'foo 'bar))> (print (list 'foo 'bar))(FOO BAR)(FOO BAR)(FOO BAR)(FOO BAR)

The most general output function in CL is The most general output function in CL is format format which takeswhich takes two or more arguments: two or more arguments: – the first indicates where the input is to be printed, the first indicates where the input is to be printed, – the second is a string template, the second is a string template, – the remaining arguments are objects whose printed the remaining arguments are objects whose printed

representations are to be inserted into the template:representations are to be inserted into the template:> (format t “~A plus ~A equals ~A.~%” 2 3 (+ 2 3))> (format t “~A plus ~A equals ~A.~%” 2 3 (+ 2 3))2 plus 3 equals 5.2 plus 3 equals 5.NILNIL

Page 52: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5252

ReadRead

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

Page 53: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5353

Local VariablesLocal Variables

One of the most frequently One of the most frequently used operators in CL is used operators in CL is letlet. . This allows local variables to This allows local variables to be used in a function.be used in a function.A let expression has two parts. A let expression has two parts. – First comes a list of instructions First comes a list of instructions

for creating variables, each of the for creating variables, each of the form form varvar or or (var(var expression)expression)..Local variables are valid within the Local variables are valid within the

body of the let.body of the let.– After the list of variables and After the list of variables and

values comes the body of values comes the body of expressions, which are evaluated expressions, which are evaluated in order.in order.

> (let ((x 100) (y 200))

(print (+ x y))

(setq x 200)

(print (+ x y))

‘foo)

300

400

foo

Page 54: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5454

A let exampleA let example> (defun ask-number ()> (defun ask-number ()

(format t “Please enter a number. “) (format t “Please enter a number. “) (let ((val (read))) (let ((val (read)))

(if (numberp val) (if (numberp val) valval

(ask-number)))) (ask-number))))ASK-NUMBERASK-NUMBER

> (ask-number)> (ask-number)Please enter a number. numberPlease enter a number. numberPlease enter a number. (this is a number)Please enter a number. (this is a number)Please enter a number. 52Please enter a number. 525252

Page 55: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5555

Global variablesGlobal variables

Global variables are visible throughout the Global variables are visible throughout the program.program.Global variables can be created by giving a Global variables can be created by giving a symbol and a value to symbol and a value to defparameter defparameter or or defvardefvar..> (defparameter *foo* 1)> (defparameter *foo* 1)*FOO**FOO*> *foo*> *foo*11> (defvar *bar* (+ *foo* 1))> (defvar *bar* (+ *foo* 1))*BAR**BAR*> *bar*> *bar*22> (defvar *bar* 33)> (defvar *bar* 33)*BAR**BAR*> *bar*> *bar*22

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.

Page 56: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5656

Global constantsGlobal constantsYou can define a global constant, by calling You can define a global constant, by calling defconstantdefconstant..

> (defconstant +limit+ 100)> (defconstant +limit+ 100)+LIMIT++LIMIT+> (setf +limit+ 99)> (setf +limit+ 99)*** - SETQ: the value of the constant +LIMIT+ may *** - SETQ: the value of the constant +LIMIT+ may

not be alterednot be altered1. Break [5]>1. Break [5]>

The plus-The plus-somethingsomething-plus is a lisp convention -plus is a lisp convention to identify symbols as constants. Just like to identify symbols as constants. Just like star-star-somethingsomething-star is a lisp convention to -star is a lisp convention to identify global variables.identify global variables.

Page 57: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5757

When in doubtWhen in doubt

When in doubt about whether some When in doubt about whether some symbol is a global variable or constant, use symbol is a global variable or constant, use boundpboundp..

> (boundp ‘*foo*)> (boundp ‘*foo*)

TT

> (boundp ‘fishcake)> (boundp ‘fishcake)

NILNIL

Page 58: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5858

AssignmentAssignment

There are several assignment operators in There are several assignment operators in Common Lisp: set, setq and setfCommon Lisp: set, setq and setfthe most general assignment operator is the most general assignment operator is setfsetf..We can use it to assign both local and global We can use it to assign both local and global variables:variables:

> (setf *blob* 89)> (setf *blob* 89)8989> (let ((n 10))> (let ((n 10)) (setf n 2)(setf n 2) n)n)22

Page 59: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5959

SetfSetfYou can create global variables implicitly just by You can create global variables implicitly just by assigning them values. assigning them values. > (setf x (list ‘a ‘b ‘c))> (setf x (list ‘a ‘b ‘c))(A B C)(A B C)

However, it is better lisp style to use However, it is better lisp style to use defparameter to declare global variables.defparameter to declare global variables.You can give setf any even number of You can give setf any even number of arguments:arguments:

(setf a 1 b 2 c 3)(setf a 1 b 2 c 3)is the same as:is the same as:

(setf a 1)(setf a 1)(setf b 2)(setf b 2)(setf c 3)(setf c 3)

Page 60: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

6060

setfsetf

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

Page 61: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

6161

Functional programmingFunctional programming

Functional programming Functional programming means writing means writing programs that work by returning values, programs that work by returning values, instead of by modifying things.instead of by modifying things.

It is the dominant programming paradigm in It is the dominant programming paradigm in Lisp.Lisp.

Must built-in lisp functions are meant to be Must built-in lisp functions are meant to be called for the values they return, not for side-called for the values they return, not for side-effects.effects.

Page 62: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

6262

Examples of functional Examples of functional programmingprogramming

The function The function removeremove takes an object and a list and returns a takes an object and a list and returns a new list containing everything but that object:new list containing everything but that object:> (setf lst ‘(b u t t e r))> (setf lst ‘(b u t t e r))(B U T T E R)(B U T T E R)> (remove ‘e lst)> (remove ‘e lst)(B U T T R)(B U T T R)

Note: remove does not remove an item from the list! The Note: remove does not remove an item from the list! The original list is untouched after the call to remove:original list is untouched after the call to remove:> lst> lst(B U T T E R)(B U T T E R)

To actually remove an item from a list you would To actually remove an item from a list you would have to use setf:have to use setf:> (setf lst (remove ‘e lst))> (setf lst (remove ‘e lst))

Functional programming means, essentially, Functional programming means, essentially, avoiding setf, and other assignment macros.avoiding setf, and other assignment macros.

Page 63: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

6363

How remove could be definedHow remove could be defined

Here’s how remove could be defined:Here’s how remove could be defined:

(defun remove (x list)(defun remove (x list) (cond ((null list) nil)(cond ((null list) nil)

((equal x (car list)) ((equal x (car list))

(remove x (cdr list)))(remove x (cdr list)))

(t (cons (car list) (remove x (cdr (t (cons (car list) (remove x (cdr list))))))list))))))

Note that it “copies” the top-level of the list.Note that it “copies” the top-level of the list.

Page 64: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

6464

IterationIterationWhen we want to do something When we want to do something repeatedly, it is sometimes more natural repeatedly, it is sometimes more natural to use iteration than recursion. to use iteration than recursion. This function uses This function uses dodo to print out the to print out the squares of the integers from squares of the integers from startstart to to endend::

(defun show-squares (start end)(defun show-squares (start end) (do ((i start (+ i 1)))(do ((i start (+ i 1))) ((> i end) ‘done)((> i end) ‘done) (format t “~A ~A~%” i (* i i))))(format t “~A ~A~%” i (* i i))))

Page 65: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

6565

dodoTheThe do do macro is CL’s fundamental iteration operator.macro is CL’s fundamental iteration operator.Like Like letlet, , dodo can create variables, and the first argument is a can create variables, and the first argument is a list of variable specifications. Each element is of the form: list of variable specifications. Each element is of the form: ((varvar initialinitial updateupdate) where ) where variablevariable is a symbol, and is a symbol, and initial initial and and updateupdate are expressions. are expressions.

The second argument to The second argument to dodo should be a list should be a list containing one or more expressions.containing one or more expressions.– The first expression is used to test whether iteration The first expression is used to test whether iteration

should stop. In the case above, the test expression is (> should stop. In the case above, the test expression is (> i end). i end).

– The remaining expression in this list will be evaluated in The remaining expression in this list will be evaluated in order when iteration stops, and the value of the last will be order when iteration stops, and the value of the last will be returned as the value of the returned as the value of the dodo, , donedone in this example. in this example.

The remaining arguments to The remaining arguments to dodo comprise the body comprise the body of the loop.of the loop.

Page 66: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

6666

DolistDolistCL has a simpler iteration operator for handling CL has a simpler iteration operator for handling lists, lists, dolistdolist..(defun len (lst)(defun len (lst) “ “I calculate the length of lst”I calculate the length of lst” (let ((l 0))(let ((l 0)) (dolist (obj lst) (setf l (+ l 1)))(dolist (obj lst) (setf l (+ l 1))) l))l))

Here dolist takes an argument of the form Here dolist takes an argument of the form ((variablevariable expressionexpression), followed by a body of ), followed by a body of expressions.expressions.The body will be evaluated with The body will be evaluated with variablevariable bound bound to successive elements of the list returned by to successive elements of the list returned by expression.expression.

Page 67: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

6767

evaleval

You can call Lisp’s evaluation process with the You can call Lisp’s evaluation process with the eval function.eval function.

> (setf s1 '(cadr '(one two three)))> (setf s1 '(cadr '(one two three)))

(CADR '(ONE TWO THREE))(CADR '(ONE TWO THREE))

> (eval s1)> (eval s1)

TWOTWO

> (eval (list 'cdr (car '((quote (a . b)) c))))> (eval (list 'cdr (car '((quote (a . b)) c))))

BB

Page 68: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

6868

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

DEFUN ADD1)) (BLOCK ADD1 (+ N 1))>DEFUN ADD1)) (BLOCK ADD1 (+ N 1))>

Page 69: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

6969

Just as we can use ‘ as an abbreviation for Just as we can use ‘ as an abbreviation for quotequote, we can use #’ as an abbreviation for , we can use #’ as an abbreviation for functionfunction::> #’+> #’+

#<SYSTEM-FUNCTION +>#<SYSTEM-FUNCTION +>

This abbreviation is known as sharp-quote.This abbreviation is known as sharp-quote.

Like any other kind of object, we can pass Like any other kind of object, we can pass functions as arguments. functions as arguments.

One function that takes a function as an One function that takes a function as an argument is argument is applyapply..

Functions as objectsFunctions as objects

Page 70: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

7070

ApplyApplyApplyApply takes a function and a list of arguments for it, takes a function and a list of arguments for it, and returns the result of applying the function to the and returns the result of applying the function to the arguments:arguments:

> (apply #’+ ‘(1 2 3))> (apply #’+ ‘(1 2 3))

66

It can be given any number of arguments, so long as It can be given any number of arguments, so long as the last is a list:the last is a list:

> (apply #’+ 1 2 ‘(3 4 5))> (apply #’+ 1 2 ‘(3 4 5))

1515

A simple version of apply could be written as A simple version of apply could be written as followsfollows

(defun apply (f list) (eval (cons f list)))(defun apply (f list) (eval (cons f list)))

Page 71: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

7171

FuncallFuncall

The function The function funcallfuncall is like is like applyapply but does not but does not need the arguments to be packaged in a list:need the arguments to be packaged in a list:

> (funcall #’+ 1 2 3)> (funcall #’+ 1 2 3)

66

It could be written as:It could be written as:

(defun funcall (f &rest args)(defun funcall (f &rest args)

(eval (cons f args)))(eval (cons f args)))

Page 72: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

7272

TypesTypesIn CL In CL valuesvalues have types, not have types, not variablesvariables..

You don’t have to declare the types of variables, You don’t have to declare the types of variables, because any variable can hold objects of any type.because any variable can hold objects of any type.

Though type declaration is never required, you Though type declaration is never required, you may want to make them for reasons of efficiency. may want to make them for reasons of efficiency.

The built-in CL types form a hierarchy of subtypes The built-in CL types form a hierarchy of subtypes and supertypes.and supertypes.

The type The type tt is the supertype of all types, so is the supertype of all types, so everything is of type everything is of type tt..

Page 73: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

7373

27

fixnum

integer

rational

real

number

atom

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

Page 74: 1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

7474

SummarySummary

LispLisp– SyntaxSyntax– RecursionRecursion– LISP facilitiesLISP facilities

Common LispCommon Lisp– http://www.cs.ucdavis.edu/~vemuri/classes/http://www.cs.ucdavis.edu/~vemuri/classes/

ecs170/lispintro.htmecs170/lispintro.htm