88
List List Processing Processing LISP LISP

List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Embed Size (px)

Citation preview

Page 1: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

List Processing List Processing LISPLISP

Page 2: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

History and MotivationHistory and Motivation

Page 3: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

The Fifth Generation Comprises The Fifth Generation Comprises Three Overlapping Paradigms Three Overlapping Paradigms

functional programmingfunctional programming

object-oriented programmingobject-oriented programming

logic programming logic programming Lisp is the functional programming.Lisp is the functional programming.

Page 4: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

The Desire for an Algebraic List-The Desire for an Algebraic List-Processing LanguageProcessing Language

Lisp develop in the 1950s out of the need Lisp develop in the 1950s out of the need of artificial intelligence programming.of artificial intelligence programming.

In these application complex In these application complex interrelationships among data must be interrelationships among data must be represented. the result is :represented. the result is :

PointerPointer

Linked listLinked list

Page 5: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

In the 1950s Newell, Shaw, and Simon (at In the 1950s Newell, Shaw, and Simon (at Carnegie institute of technology and the Carnegie institute of technology and the rand corporation) developed many of the rand corporation) developed many of the ideas of list processing in the IPL family of ideas of list processing in the IPL family of programming languages. these ideas programming languages. these ideas included the linked representation of list included the linked representation of list structures and the use of a stack structures and the use of a stack (specifically, a push-down list) to (specifically, a push-down list) to implement recursion.implement recursion.

Page 6: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

In the summer of 1956, the first major workshop In the summer of 1956, the first major workshop on artificial intelligence was held at Dartmouth.on artificial intelligence was held at Dartmouth. At this workshop john McCarthy, then at MIT, At this workshop john McCarthy, then at MIT, heard a description of the ipl2 programming heard a description of the ipl2 programming language.language. which had a tow-level pseudo-code, or which had a tow-level pseudo-code, or assembly-language-like syntax.assembly-language-like syntax. McCarthy realized that an algebraic list-McCarthy realized that an algebraic list-processing language, on the style of the recently processing language, on the style of the recently announced fortran I system, would be very announced fortran I system, would be very usefull.usefull.

Page 7: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

FLPL Was Based on FortranFLPL Was Based on Fortran

That summer Gerlernter and Gerberich of IBM That summer Gerlernter and Gerberich of IBM were working, with the advice of McCarthy, on a were working, with the advice of McCarthy, on a geometry program. As a tool they developed geometry program. As a tool they developed FLPL, the Fortran list-processing language, by FLPL, the Fortran list-processing language, by writing a set of list-processing subprograms for writing a set of list-processing subprograms for use with Fortran programs.use with Fortran programs.

One result of this work was the development of One result of this work was the development of the basic list-processing primitives that were the basic list-processing primitives that were later incorporated into lisp.later incorporated into lisp.

Page 8: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

McCarthy Developed the Central McCarthy Developed the Central Ideas of LISPIdeas of LISP

FORTRAN I had only one conditional constructFORTRAN I had only one conditional construct—the arithmetic IF-statement.—the arithmetic IF-statement. This construct was very inconvenient for list This construct was very inconvenient for list processing.processing. which led McCarthy, in 1957, to write an IF which led McCarthy, in 1957, to write an IF function with three arguments:function with three arguments:

X = IF (N .EQ. 0, ICAR(Y) , ICDR(Y))X = IF (N .EQ. 0, ICAR(Y) , ICDR(Y))If N were zero, then X = ICAR(Y) else X = If N were zero, then X = ICAR(Y) else X =

ICDR(Y)ICDR(Y)

Page 9: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

An important consequence of this An important consequence of this invention was that it made it feasible to invention was that it made it feasible to compose IF function and the list-compose IF function and the list-processing functions to achieve more processing functions to achieve more complicated actionscomplicated actions..

Since FORTRAN does not permit recursive Since FORTRAN does not permit recursive definitions, it became apparent that a new definitions, it became apparent that a new language was needed.language was needed.In 1958 McCarthy began using recursion in In 1958 McCarthy began using recursion in conjunction with conditional expression in conjunction with conditional expression in his definition of list-processing functions. his definition of list-processing functions.

Page 10: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

The Lisp List-Handling Routines The Lisp List-Handling Routines Were Developed FirstWere Developed First

in the fall of 1958, implementation of a LISP in the fall of 1958, implementation of a LISP system began.system began. One important component of this was a set One important component of this was a set of primitive list-handling subroutines for the of primitive list-handling subroutines for the lisp run-time environment.lisp run-time environment. These were the first parts of the system that These were the first parts of the system that were implemented. were implemented. The original intention was to develop a The original intention was to develop a compiler like FORTRAN. compiler like FORTRAN. Therefore, to gain experience in code Therefore, to gain experience in code generation, a number of LISP programs were generation, a number of LISP programs were hand comiled into assembly language.hand comiled into assembly language.

Page 11: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

A LISP Universal Function A LISP Universal Function Resulted in an InterpreterResulted in an Interpreter

McCarthy became convinced that McCarthy became convinced that recursive list-processing functions with recursive list-processing functions with conditional expressions formed an easier-conditional expressions formed an easier-to-understand basis for the theory of to-understand basis for the theory of computation than did other formalisms computation than did other formalisms such as Turing machines. such as Turing machines. Recursive Functions of Symbolic Recursive Functions of Symbolic Expressions and Their Computation by Expressions and Their Computation by Machine.Machine.

Page 12: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

He defined a universal LISP function that He defined a universal LISP function that could interpret any other lisp function.could interpret any other lisp function.

he wrote a LISP interpreter in LISP. Since he wrote a LISP interpreter in LISP. Since manipulates only lists, writing a universal manipulates only lists, writing a universal function required developing a way of function required developing a way of representing LISP program as list representing LISP program as list structures. structures.

Page 13: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

For example the function callFor example the function call

F [x+y; u*z]F [x+y; u*z]

Would be represented by a list whose first Would be represented by a list whose first element is ‘f’ and whose second and third element is ‘f’ and whose second and third element are the lists representing ’x+y’ element are the lists representing ’x+y’ and ‘u*z’. in LISP list is written and ‘u*z’. in LISP list is written

(f (plus x y) (times u z) )(f (plus x y) (times u z) )

Page 14: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

The algol-like notation (e,g., f[x+y; The algol-like notation (e,g., f[x+y; u*z]) is called M-u*z]) is called M-expressionsexpressions (M for (M for meta-language).meta-language).

The list notation is called S-The list notation is called S-expressionsexpressions (S for symbolic (S for symbolic language)language)

Page 15: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

LISP Became Widely Used in LISP Became Widely Used in Artificial IntelligenceArtificial Intelligence

The first implementation of LISP was on IBM The first implementation of LISP was on IBM 704 704 LISP systems rapidly spread to other computers, LISP systems rapidly spread to other computers, and they now exist on virtually all machines, and they now exist on virtually all machines, including microcomputers.including microcomputers. LISP has become the most widely used LISP has become the most widely used programming language for artificial intelligence programming language for artificial intelligence and other symbolic applications.and other symbolic applications.LISP was standardized after a period of LISP was standardized after a period of divergent evolutiondivergent evolution

Page 16: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

DESIG: STRUCTURAL DESIG: STRUCTURAL ORGANIZATIONORGANIZATION

An Example LISP Program (in the S-An Example LISP Program (in the S-expression)expression)

Page 312 Page 312

Page 17: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Function Application Is the Function Application Is the Central IdeaCentral Idea

programming language are often divided programming language are often divided into tow classes:into tow classes:Imperative languageImperative language

Depend heavily on an assignment Depend heavily on an assignment statement and a changeable memory for statement and a changeable memory for accomplishing a programming task.accomplishing a programming task.Applicative languageApplicative language

The central idea is function application, that The central idea is function application, that is, applying a function to its argument .is, applying a function to its argument .

Page 18: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

In the LISP almost everything is a function In the LISP almost everything is a function application application

((f a1 a2…an)f a1 a2…an)

where f is the function and a1, a2, …, an are the where f is the function and a1, a2, …, an are the arguments. This notation is called arguments. This notation is called Combridge Combridge Polish (prefix notation).Polish (prefix notation).

Example:Example: (plus 2 3)(plus 2 3) (plus 10 5 8 64)(plus 10 5 8 64)

LISP is LISP is fully fully parenthesized parenthesized

Page 19: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

ExampleExample

(set ‘Freq (make-table text nil))(set ‘Freq (make-table text nil))is a nested function application : set is is a nested function application : set is applied to tow arguments: applied to tow arguments: freq freq the result of applying make-table to the the result of applying make-table to the arguments text and nil. arguments text and nil. In an algol-like language this would be In an algol-like language this would be writtenwritten

set (Freq, mqke-table (text, nil))set (Freq, mqke-table (text, nil))

Page 20: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

ExampleExample

(cond (cond

((null x) 0) ((null x) 0)

((eq x y) (f x))((eq x y) (f x))

(t (g y)) )(t (g y)) )

In an Algol-like language this would be writtenIn an Algol-like language this would be written

If If null(x) null(x) then then 00

elseif elseif x = yx = y then then f(x)f(x)

else else g(y) g(y) endifendif

Page 21: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

function definition is accomplish by function definition is accomplish by calling a function, defun, with three calling a function, defun, with three arguments: the name of the function, arguments: the name of the function, its formal parameter list, and its boby.its formal parameter list, and its boby.

Page 22: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Why is everything a function Why is everything a function application in LISP?application in LISP?

Simplicity PrincipleSimplicity PrincipleIf there is only one basic mechanism in a If there is only one basic mechanism in a language, the language is easier to learn, language, the language is easier to learn, understand, and implement.understand, and implement.

Page 23: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

The List Is the Primary Data The List Is the Primary Data Structure ConstructorStructure Constructor

We said that one of LISP’s goals was to allow We said that one of LISP’s goals was to allow computation with Symbolic data.computation with Symbolic data. This is accomplished by allowing the programmer to This is accomplished by allowing the programmer to manipulate lists of data. manipulate lists of data. Example:Example:

((set ‘text ‘ (to be or not to be))set ‘text ‘ (to be or not to be)) the second argument to set is the listthe second argument to set is the list (to be or not to be)(to be or not to be)

This list above is composed of four distinct atoms:This list above is composed of four distinct atoms: to be or notto be or not

Page 24: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

LISP manipulates list just like other LISP manipulates list just like other languages manipulate number; they can languages manipulate number; they can be compared, passed to functions, put be compared, passed to functions, put together, and taken apart.together, and taken apart.

Page 25: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Programs Are Represented as Programs Are Represented as ListsLists

Function application and lists look the same.Function application and lists look the same. (make-table text nil)(make-table text nil)

could either be a three-element list whose could either be a three-element list whose elements are the make-table, text, nil; or it could elements are the make-table, text, nil; or it could be an application of the function make-table to be an application of the function make-table to the arguments named text and nil. Because a the arguments named text and nil. Because a LISP program is itself a list.LISP program is itself a list.If the list is quoted, then it is treated as data; that If the list is quoted, then it is treated as data; that is, it is unevaluated..is, it is unevaluated..

Page 26: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

If the list is quoted, then it is treated as If the list is quoted, then it is treated as data; that is, it is unevaluated.data; that is, it is unevaluated.

Example:Example:

(set ‘text ‘ (to be or not to be))(set ‘text ‘ (to be or not to be))

(set ‘text (to be or not to be))(set ‘text (to be or not to be))

Page 27: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

the fact that LISP represents both programs the fact that LISP represents both programs and data in the same way of the utmost and data in the same way of the utmost importance:importance:

it makes it very easy to write a LISP interpreter it makes it very easy to write a LISP interpreter in LISP.in LISP.it makes it convenient to have one LISP program it makes it convenient to have one LISP program generate and call for the execution of another generate and call for the execution of another LISP program.LISP program.It also simplifies writing LISP programs that It also simplifies writing LISP programs that transform and manipulate other LISP programs.transform and manipulate other LISP programs.

Page 28: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

These capabilities are important in artificial These capabilities are important in artificial intelligence and other advanced programintelligence and other advanced program--development environmentsdevelopment environments..

These amplification come with a reduction These amplification come with a reduction of readabilityof readability..

Page 29: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

LISP Is Often InterpretedLISP Is Often Interpreted

Most LISP systems provide interactive interpreters. We Most LISP systems provide interactive interpreters. We interact with the LISP interpreter by typing in function interact with the LISP interpreter by typing in function applications. The LISP system then interprets them and applications. The LISP system then interprets them and point out the result.point out the result.Example:Example:

(plus 2 3)(plus 2 3) the system will respondthe system will respond 55

Similarly if we typeSimilarly if we type (eq (plus 2 3) (difference 9 4))(eq (plus 2 3) (difference 9 4)) the system will respond the system will respond tt

Page 30: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Pure FunctionPure Function

functions like eq and plus are pure functions like eq and plus are pure function function ((or simply functionsor simply functions) ) because they because they have no effect other than the computation have no effect other than the computation of a valueof a value..

Pure functions obey the Manifest Interface Pure functions obey the Manifest Interface Principle because their interfaces are Principle because their interfaces are apparent apparent ((manifestmanifest).).

Page 31: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

The Manifest Interface The Manifest Interface PrinciplePrinciple

All interfaces should be All interfaces should be apparent (manifest) in the apparent (manifest) in the syntax.syntax.

Page 32: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Procedure’sProcedure’sSome function in LISP are pseudo-function (or Some function in LISP are pseudo-function (or procedure). These are functions that have a side procedure). These are functions that have a side effect on the state of computer in addition to effect on the state of computer in addition to computing a result.computing a result.Example:Example:

(set ‘text ‘(to be or not to be))(set ‘text ‘(to be or not to be))binds the name (atom) text to the (to be or not to binds the name (atom) text to the (to be or not to be) that it is a list and return this list.be) that it is a list and return this list.The atom n can now be used as a name for this The atom n can now be used as a name for this list in any expression, for examplelist in any expression, for example

(set ‘Freq (make-table text nil))(set ‘Freq (make-table text nil))

Page 33: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

FunctionFunction

another importanr pseudo-function is defun, another importanr pseudo-function is defun, which define a function.which define a function.Example:Example:

(defun f (x1,x2, …, xn) b)(defun f (x1,x2, …, xn) b)defines a function with the name f, formal defines a function with the name f, formal parameters x1, x2, … , xn; and body bparameters x1, x2, … , xn; and body b The function application used to define The function application used to define functions is different in many dialects.functions is different in many dialects.in LISP the binding process is dynamic, that is, it in LISP the binding process is dynamic, that is, it take the place at run-time.take the place at run-time.

Page 34: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

DESIGN: DATA STRUCTUREDESIGN: DATA STRUCTURE

Page 35: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

The Primitives Include Numeric The Primitives Include Numeric AtomsAtoms

We classify LISP data structure (like other We classify LISP data structure (like other languages) into languages) into primitiveprimitive and and constructorsconstructors..The principle The principle constructorconstructor is the list: it permits is the list: it permits more complicated structures to be built from more complicated structures to be built from simpler structures. simpler structures. The primitive data structures are the starting The primitive data structures are the starting points to building process. Thus, the primitive points to building process. Thus, the primitive are those data structure that are not build from are those data structure that are not build from any other: they have no parts. It is for this any other: they have no parts. It is for this reason that they are called atoms.reason that they are called atoms.

Page 36: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

There are at least tow types of atoms in There are at least tow types of atoms in all LISP systems:all LISP systems:

NumericNumeric

NonnumericNonnumeric

Page 37: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

LISP provides a very large set of primitive LISP provides a very large set of primitive functions for manipulating numeric atoms:functions for manipulating numeric atoms:Arithmetic operations (plus, difference, etc.)Arithmetic operations (plus, difference, etc.)Predecessor and successor function (sub1, Predecessor and successor function (sub1, add1)add1)Maximum and minimum functionsMaximum and minimum functionsRelation tests (equal, lessp, greaterp)Relation tests (equal, lessp, greaterp)Predicates (i.e., tests, such as zerop, onep, Predicates (i.e., tests, such as zerop, onep, minusp)minusp)

Page 38: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

All of these function take both integer and All of these function take both integer and floating-point (and in some systems, floating-point (and in some systems, multiple-precision) arguments and return multiple-precision) arguments and return results of the appropriate type.results of the appropriate type.

Page 39: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

ExampleExample

LISP’s use of Combridge Polish limits its LISP’s use of Combridge Polish limits its numerical applications.numerical applications.Example:Example:

(-b + √(b² - 4ac) ) /2a(-b + √(b² - 4ac) ) /2amust be written must be written

(quotient (plus (minus b)(quotient (plus (minus b) (sqrt (difference (expt b 2)(sqrt (difference (expt b 2)

(times 4 a c))))(times 4 a c))))(times 2 a)(times 2 a)

Page 40: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Nonnumeric Atoms Are Also Nonnumeric Atoms Are Also ProvidedProvided

These atoms are strings of characters that These atoms are strings of characters that were originally intended to represent were originally intended to represent words or symbols.words or symbols.

Page 41: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

ExampleExample

With few exceptions, the only operations With few exceptions, the only operations that can be performed on nonnumeric that can be performed on nonnumeric atoms are comparisions for equality and atoms are comparisions for equality and inequality. This is done with function inequality. This is done with function eq:eq:

Example:Example:

((eq eq x y)x y)

t if x and y are the same atom,t if x and y are the same atom,

nnil if x and y are not the same atom,il if x and y are not the same atom,

Page 42: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

the atom nil has many uses in LISPthe atom nil has many uses in LISP. . This This operation is often used as a base for operation is often used as a base for recursive definitionsrecursive definitions..

((eq x nileq x nil))

((null xnull x))

nil is the noun and null is the nil is the noun and null is the corresponding adjectivecorresponding adjective..

Page 43: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Some LISP systems provide additional Some LISP systems provide additional types of atoms, such as strings. In these types of atoms, such as strings. In these cases special operations for manipulating cases special operations for manipulating these values are also providedthese values are also provided

Page 44: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Abstract Data TypeAbstract Data Type

An abstract data type is a set of data An abstract data type is a set of data values together with a set of operations values together with a set of operations on those values.on those values.

Page 45: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

The Principal Constructor Is the The Principal Constructor Is the ListList

The characteristic method of data structuring The characteristic method of data structuring provided by LISP is called the provided by LISP is called the list. list. Lists are written in the S-expression notation by Lists are written in the S-expression notation by surrounding with parentheses the list’s elements, surrounding with parentheses the list’s elements, which are separated by blanks.which are separated by blanks. Lists can have none, one, or more elements, so Lists can have none, one, or more elements, so they satisfy the Zero-One-Infinity Principle. The they satisfy the Zero-One-Infinity Principle. The elements of lists can themselves be lists, so the elements of lists can themselves be lists, so the Zero-One-Infinity Principle is also satisfied by Zero-One-Infinity Principle is also satisfied by the nesting level of lists.the nesting level of lists.

Page 46: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

The empty list, ( ) is considered equivalent The empty list, ( ) is considered equivalent to the atom to the atom nil:nil:

(eq ‘( ) nil)(eq ‘( ) nil)

oror

(null ‘( ) )(null ‘( ) )

Except the null list all lists are nonatomic, Except the null list all lists are nonatomic, they are sometimes called composite data they are sometimes called composite data values.values.

Page 47: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

We ca find out whether or not something is an atom by We ca find out whether or not something is an atom by using the atom predicate.using the atom predicate.Example:Example:(atom ‘to)(atom ‘to)

tt(atom (plus 2 3))(atom (plus 2 3))

tt(atom nil)(atom nil)

tt(atom ‘(to be) ) (atom ‘(to be) )

nilnil(atom ‘( ( ) ) )(atom ‘( ( ) ) )

nilnilNotice neither ( ( ) ) nor (nil) is the null listNotice neither ( ( ) ) nor (nil) is the null list

Page 48: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Constructor and SelectorConstructor and Selector

Operations that build a structure are Operations that build a structure are called constructors.called constructors.

OperationOperation that extract their parts are that extract their parts are called selectors.called selectors.

Page 49: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Car and Cdr Access the Parts of Car and Cdr Access the Parts of ListsLists

Car : return the first element of the list.Car : return the first element of the list.

Cdr : returns all of a list except its first element.Cdr : returns all of a list except its first element.

Example:Example:

(car ‘(to be or not to be) )(car ‘(to be or not to be) )

returns the atom toreturns the atom to

(cdr ‘(to be or not to be) )(cdr ‘(to be or not to be) )

returns the list returns the list

(be or not to be)(be or not to be)

Page 50: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Notice that the argument to car and cdr is Notice that the argument to car and cdr is always a nonnull listalways a nonnull list..

Unlike car, cdr always returns a listUnlike car, cdr always returns a list..

Car and Cdr are pure functionCar and Cdr are pure function. . The easiest The easiest way to think of the way they work is that way to think of the way they work is that they make a new copy of the listthey make a new copy of the list..

Page 51: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Car and Cdr can be used in Car and Cdr can be used in combination to access the combination to access the

components of a listcomponents of a list

Example:Example:

(set ‘DS ‘(Don Smith) 45 30000 (set ‘DS ‘(Don Smith) 45 30000 (august 25 1980) ) )(august 25 1980) ) )

(car (cdr (cdr (cdr DS))))(car (cdr (cdr (cdr DS))))

returns the listreturns the list

(august 25 1980)(august 25 1980)

Page 52: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

In general, the nth element of a list can be In general, the nth element of a list can be access by n-1 cdrs followed by a car.access by n-1 cdrs followed by a car.

The composition of cars and cdrs is represented The composition of cars and cdrs is represented by the sequence of ‘a’s and ‘d’s between the by the sequence of ‘a’s and ‘d’s between the initial ‘c’ and the final ‘r’.initial ‘c’ and the final ‘r’.

This can be seen more clearly if the list is written This can be seen more clearly if the list is written as a linked data structure; then a ‘d’ moves to as a linked data structure; then a ‘d’ moves to the right and an ‘a’ moves down.the right and an ‘a’ moves down.

Page 53: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Figure 9.2Figure 9.2

Page 54: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Clearly, these sequence of ‘a’s and ‘d’s Clearly, these sequence of ‘a’s and ‘d’s can become quite complicated to read. can become quite complicated to read. Writing them is also error-prone.Writing them is also error-prone. One solution to this is to write a set of One solution to this is to write a set of special-purpose functions for accessing special-purpose functions for accessing the part of a record. For example a the part of a record. For example a function for accessing the hire date could function for accessing the hire date could be defined asbe defined as(defun hire-date (r) (cadddr))(defun hire-date (r) (cadddr))Then (hire-date DS) returns Don Smith Then (hire-date DS) returns Don Smith hire datehire date

Page 55: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Information Can Be Represented Information Can Be Represented by Property Listsby Property Lists

A personnel record would probably not be A personnel record would probably not be represented in LISP in the way we have just represented in LISP in the way we have just described: it is too inflexible. A better described: it is too inflexible. A better arrangement is to precede each of information arrangement is to precede each of information with an indicator identifying the property.with an indicator identifying the property.Example:Example: (name (Don Smith) age 45 salary 30000 (name (Don Smith) age 45 salary 30000 hire-date (august 25 1980) )hire-date (august 25 1980) )this method of representing information is called this method of representing information is called a a property list property list or p-list. Its general form isor p-list. Its general form is

(P1 v1 P2 v2 … Pn vn)(P1 v1 P2 v2 … Pn vn)each Pi is the indicator for a property and each each Pi is the indicator for a property and each Vi is the corresponding property valueVi is the corresponding property value

Page 56: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

How can the properties of a pHow can the properties of a p--list list be accessed?be accessed?

(defun getprop (p x)(defun getprop (p x)

(if (eq (car x) p)(if (eq (car x) p)

(cadr x)(cadr x)

(getprop p (cddr x)) ))(getprop p (cddr x)) ))

Example:Example:

(getprop ‘name DS)(getprop ‘name DS)

ReturnReturn (Don Smith) (Don Smith)

Page 57: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

What will this function do if ask for a What will this function do if ask for a property that is not in the property list?property that is not in the property list?

(getprop ‘weight DS)(getprop ‘weight DS)

Error: car of nilError: car of nil

Page 58: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

One way to do this is to have getprop One way to do this is to have getprop return a distinguished value if the return a distinguished value if the property does not exist. An obvious property does not exist. An obvious choice is nil, but this would not be choice is nil, but this would not be agood choice since it would then be agood choice since it would then be impossible to distinguish an impossible to distinguish an undefined property from one that is undefined property from one that is defined but whose value is nil.defined but whose value is nil.

Page 59: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

A better decision is to pick some atom, A better decision is to pick some atom, such as undefined-property, which is such as undefined-property, which is unlikely to be used for any other purposeunlikely to be used for any other purpose

(getprop ‘weight DS)(getprop ‘weight DS)

undefined-propertyundefined-property

Page 60: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Information Can Be Represented in Information Can Be Represented in Association ListAssociation List

The property list data structure works best The property list data structure works best when exactly one value is to be associated when exactly one value is to be associated with each property. Some properties are flags with each property. Some properties are flags that have no associated value for example that have no associated value for example retired flag in our personnel record.retired flag in our personnel record.

if a property has several associated values for if a property has several associated values for example the manages property might be example the manages property might be associated with the names of everyone associated with the names of everyone managed by Don Smith.managed by Don Smith.

Page 61: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

but this is sometimes but this is sometimes inconvenientinconvenient

Some properties are flags that have no Some properties are flags that have no associated value for example retired associated value for example retired flag in our personnel recordflag in our personnel record..

if a property has several associated if a property has several associated values for example the manages values for example the manages property might be associated with the property might be associated with the names of everyone managed by Don names of everyone managed by Don Smith.Smith.

Page 62: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

These problems are solved by another These problems are solved by another common LISP data structure, the common LISP data structure, the association list, association list, or or a-lista-list..

An An a-lista-list is a list of pairs. is a list of pairs.

The general form of an The general form of an a-lista-list is a list of is a list of attribute-value pairs:attribute-value pairs:

((a1 v1) (a2 v2)…(an vn))((a1 v1) (a2 v2)…(an vn))

Page 63: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

AssocAssocThe function that does the forward The function that does the forward association. association.

For exampleFor example

(assoc ‘hire-date DS )(assoc ‘hire-date DS )

Return Return (August 25 1980)(August 25 1980)

Page 64: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Cons Constructs ListsCons Constructs Lists

The constructors undo what the selectors The constructors undo what the selectors do and vice versa, this lead to that the do and vice versa, this lead to that the data type will be more regulardata type will be more regular..

QuizQuiz::

((cons ‘cons ‘((a ba b) ) ‘‘((c dc d))))

Page 65: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Example:Example:

(cons ‘to ‘(be or not to be))(cons ‘to ‘(be or not to be))

return the list return the list

(to be or not to be)(to be or not to be)

(car ‘(to be or not to be)) = to(car ‘(to be or not to be)) = to

(cdr ‘(to be or not to be)) = (be or not to (cdr ‘(to be or not to be)) = (be or not to be))be))

(cons ‘to ‘(be or not to be)) = (to be or not to (cons ‘to ‘(be or not to be)) = (to be or not to be)be)

Page 66: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Notice that the second argument of cons Notice that the second argument of cons must be a list.must be a list.

Cons is a pure function.Cons is a pure function.

Page 67: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

List Are Usually Constructed List Are Usually Constructed RecursivelyRecursively

Page 68: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

AppendAppend

(append M L) will return the (append M L) will return the concatenation of the lists L and M.concatenation of the lists L and M.

(append ‘( ) L) = L(append ‘( ) L) = L

(append L ‘( )) = L(append L ‘( )) = L

(append ‘(b c) ‘(d e f)) = (b c d e(append ‘(b c) ‘(d e f)) = (b c d e

Page 69: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Atoms Have PropertiesAtoms Have Properties

LISP was originally developed for artificial LISP was originally developed for artificial intelligence application. These application intelligence application. These application often must deal with the properties of often must deal with the properties of objects and the relationship among objects and the relationship among objects. objects.

Page 70: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

In LISP, objects are represented by atoms, In LISP, objects are represented by atoms, and each atom has an associated p-list and each atom has an associated p-list that represents the properties of the atom that represents the properties of the atom and the relationship in which it and the relationship in which it participates. participates.

Figure 9.4 Figure 9.4

Page 71: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

In Figure In Figure

the small circles represent the objects the small circles represent the objects (atoms), and the line show their properties.(atoms), and the line show their properties.

Each of these objects comes complete Each of these objects comes complete with a property, its with a property, its print name, print name, which is a which is a character string tagged by pname.character string tagged by pname.

The print name of an atom is analogous to The print name of an atom is analogous to a proper name in English.a proper name in English.

Page 72: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

How are other property attached to How are other property attached to an atom?an atom?

Example:Example: (putprop ‘France ‘Paris ‘capital)(putprop ‘France ‘Paris ‘capital)

Return Return ParisParisWe can find out the value of a property with the We can find out the value of a property with the getget function: function:

(get ‘France ‘capital)(get ‘France ‘capital)Return Return ParisParisFigure 9.7Figure 9.7

Page 73: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Figure 9.7Figure 9.7

Page 74: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Binding atoms to lists:Binding atoms to lists:

(Set ‘Europe ‘(England France …)(Set ‘Europe ‘(England France …)

(get ‘Europe ‘apval)(get ‘Europe ‘apval)

(England France Spain …)(England France Spain …)

Page 75: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Binding of atoms to functions is Binding of atoms to functions is represented by the represented by the exprexpr property property

(Get ‘getprop ‘expr)(Get ‘getprop ‘expr)

{function expr){function expr)

Defun equivalent to putpropDefun equivalent to putprop

Page 76: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

List Have a Simple List Have a Simple RepresentationRepresentation

LISP lists are usually implemented as LISP lists are usually implemented as linked structurelinked structure. . For instance, the listFor instance, the list

((to be or not to beto be or not to be))

is represented as a sequence of six cells is represented as a sequence of six cells in memory, each containing a pointer to in memory, each containing a pointer to the nextthe next. . Each cell also contains a pointer Each cell also contains a pointer to the element of the list it representsto the element of the list it represents..

Page 77: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Figure 9.8Figure 9.8

Page 78: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

List containing other lists are represented List containing other lists are represented in the same way. For example, the listin the same way. For example, the list

( (to 2) (be 2) (or 1) (not 1) )( (to 2) (be 2) (or 1) (not 1) )

would be represented in storage as shown would be represented in storage as shown in below.in below.

Page 79: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Figure 9.9Figure 9.9

Page 80: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

The List Primitive Are Simple The List Primitive Are Simple and Efficientand Efficient

Car Car

A := L↑ . left;A := L↑ . left;

CdrCdr

D := L↑ . rightD := L↑ . right

Page 81: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Figure 9.10Figure 9.10

Page 82: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

ConsCons

L↑ L↑ . . left left : = : = A;A;

L↑ L↑ . . right right := := D;D;

Page 83: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Sublists can be sharedSublists can be shared

– Memory efficiencyMemory efficiency– Aliasing danger:Aliasing danger:

Change the conent of memoryChange the conent of memory

Because car,cdr,cons don’t infect memory it’s Because car,cdr,cons don’t infect memory it’s danger freedanger free

Page 84: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Figure 9.11Figure 9.11

Page 85: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

List Structures Can Be ModifiedList Structures Can Be Modified

rplaca (replace address part)rplaca (replace address part) rplacd (replace decrement part)rplacd (replace decrement part)

(set 'text '(to be or not to be))(set 'text '(to be or not to be)) (to be or not to be)(to be or not to be) ( set 'x (cdr text))( set 'x (cdr text)) (be or not to be)(be or not to be) (rplacd x '(is all))(rplacd x '(is all)) (be is all)(be is all)

ttextext(to be is all)(to be is all)

Danger of unwanted memory changeDanger of unwanted memory change

Page 86: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Atoms are pointers to their property Atoms are pointers to their property listslists

In implementation atoms are equivalent to In implementation atoms are equivalent to memory locationsmemory locations

Page 87: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Figure 9.13Figure 9.13

Page 88: List Processing LISP. History and Motivation The Fifth Generation Comprises Three Overlapping Paradigms functional programming object-oriented programming

Quiz Quiz

2) Draw the cons-cells construction of the 2) Draw the cons-cells construction of the list below: list below:

('Name '(John Smith) 'age '27 'salary '3000 ('Name '(John Smith) 'age '27 'salary '3000 'hire-date '(August 25 1980)) 'hire-date '(August 25 1980))