maclennan chap9 lisp

Upload: rct85

Post on 04-Apr-2018

231 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 Maclennan Chap9 Lisp

    1/90

    List ProcessingList Processing

    LISPLISPMacLennan- Chap. 9MacLennan- Chap. 9

  • 7/31/2019 Maclennan Chap9 Lisp

    2/90

    22

    History and MotivationHistory and Motivation

  • 7/31/2019 Maclennan Chap9 Lisp

    3/90

    33

    The Fifth Generation ComprisesThe Fifth Generation Comprises

    Three Overlapping ParadigmsThree Overlapping Paradigms

    functional programmingfunctional programmingobject-oriented programmingobject-oriented programminglogic programminglogic programming

    Lisp is for functional programming.Lisp is for functional programming.

  • 7/31/2019 Maclennan Chap9 Lisp

    4/90

    44

    The Desire for an Algebraic List-The Desire for an Algebraic List-

    Processing LanguageProcessing LanguageLisp is developed in the 1950s for artificialLisp is developed in the 1950s for artificialintelligence programming.intelligence programming.

    In these applications complexIn these applications complexinterrelationships among data must beinterrelationships among data must berepresented.represented.

    Natural data structures are:Natural data structures are: PointersPointers Linked listsLinked lists

  • 7/31/2019 Maclennan Chap9 Lisp

    5/90

    55

    In the 1950s Newell, Shaw, and Simon (atIn the 1950s Newell, Shaw, and Simon (at

    Carnegie institute of technology and theCarnegie institute of technology and theRand Corporation) developed many of theRand Corporation) developed many of theideas of list processing in the IPL family ofideas of list processing in the IPL family of

    programming languages. these ideasprogramming languages. these ideasincluded the linked representation of listincluded the linked representation of liststructures and the use of a stackstructures and the use of a stack(specifically, a push-down list) to(specifically, a push-down list) toimplement recursion.implement recursion.

  • 7/31/2019 Maclennan Chap9 Lisp

    6/90

    66

    In the summer of 1956, the first major workshopIn the summer of 1956, the first major workshopon 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 programmingheard a description of the ipl2 programming

    language.language.which had a low-level pseudo-code, orwhich had a low-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 recentlyprocessing language, on the style of the recentlyannounced FORTRAN I system, would be veryannounced FORTRAN I system, would be veryuseful.useful.

  • 7/31/2019 Maclennan Chap9 Lisp

    7/90

    77

    FLPL Was Based on FortranFLPL Was Based on Fortran

    That summer Gerlernter and Gerberich of IBMThat summer Gerlernter and Gerberich of IBMwere working, with the advice of McCarthy, on awere working, with the advice of McCarthy, on ageometry program. As a tool they developedgeometry program. As a tool they developed

    FLPL, the Fortran list-processing language, byFLPL, the Fortran list-processing language, bywriting a set of list-processing subprograms forwriting a set of list-processing subprograms foruse with Fortran programs.use with Fortran programs.

    One result of this work was the development ofOne result of this work was the development of

    the basic list-processing primitives that werethe basic list-processing primitives that werelater incorporated into lisp.later incorporated into lisp.

  • 7/31/2019 Maclennan Chap9 Lisp

    8/90

    88

    McCarthy Developed the CentralMcCarthy Developed the Central

    Ideas of LISPIdeas of LISP

    FORTRAN I had only one conditional constructFORTRAN I had only one conditional constructthe arithmetic IF-statement.the arithmetic IF-statement.This construct was very inconvenient for listThis construct was very inconvenient for list

    processing.processing.which led McCarthy, in 1957, to write an IFwhich led McCarthy, in 1957, to write an IFfunction 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)

  • 7/31/2019 Maclennan Chap9 Lisp

    9/90

    99

    An important consequence of thisAn important consequence of thisinvention was that it made it feasible toinvention was that it made it feasible tocompose IF function and the list-compose IF function and the list-processing functions to achieve moreprocessing functions to achieve morecomplicated actionscomplicated actions..Since FORTRAN does not permitSince FORTRAN does not permitrecursive definitions, it became apparentrecursive definitions, it became apparentthat a new language was needed.that a new language was needed.

    In 1958 McCarthy began using recursionIn 1958 McCarthy began using recursionin conjunction with conditional expressionin conjunction with conditional expressionin his definition of list-processing functions.in his definition of list-processing functions.

  • 7/31/2019 Maclennan Chap9 Lisp

    10/90

    1010

    The Lisp List-Handling RoutinesThe Lisp List-Handling Routines

    Were Developed FirstWere Developed Firstin the fall of 1958, implementation of a LISPin the fall of 1958, implementation of a LISPsystem began.system began.

    One important component of this was a setOne important component of this was a setof primitive list-handling subroutines for theof primitive list-handling subroutines for the

    lisp run-time environment.lisp run-time environment.These were the first parts of the system thatThese were the first parts of the system that

    were implemented.were implemented.

    The original intention was to develop aThe original intention was to develop a

    compiler like FORTRAN.compiler like FORTRAN.Therefore, to gain experience in codeTherefore, to gain experience in codegeneration, a number of LISP programs weregeneration, a number of LISP programs werehand compiled into assembly language.hand compiled into assembly language.

  • 7/31/2019 Maclennan Chap9 Lisp

    11/90

    1111

    A LISP Universal FunctionA LISP Universal Function

    Resulted in an InterpreterResulted in an InterpreterMcCarthy became convinced thatMcCarthy became convinced thatrecursive list-processing functions withrecursive list-processing functions withconditional expressions formed an easier-conditional expressions formed an easier-

    to-understand basis for the theory ofto-understand basis for the theory ofcomputation than other formalisms suchcomputation than other formalisms suchas Turing machines.as Turing machines.

    Recursive Functions of SymbolicRecursive Functions of SymbolicExpressions and Their Computation byExpressions and Their Computation byMachine.Machine.

  • 7/31/2019 Maclennan Chap9 Lisp

    12/90

    1212

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

    he wrote a LISP interpreter in LISP. Sincehe wrote a LISP interpreter in LISP. Sincemanipulates only lists, writing a universalmanipulates only lists, writing a universalfunction required developing a way offunction required developing a way ofrepresenting LISP program as listrepresenting LISP program as list

    structures.structures.

  • 7/31/2019 Maclennan Chap9 Lisp

    13/90

    1313

    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 firstWould be represented by a list whose firstelement is f and whose second and thirdelement is f and whose second and third

    element are the lists representing x+yelement are the lists representing x+yand u*z. in LISP this list is written asand u*z. in LISP this list is written as

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

  • 7/31/2019 Maclennan Chap9 Lisp

    14/90

    1414

    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 language)(S for symbolic language)

  • 7/31/2019 Maclennan Chap9 Lisp

    15/90

    1515

    LISP Became Widely Used inLISP Became Widely Used in

    Artificial IntelligenceArtificial IntelligenceThe first implementation of LISP was on IBM 704The first implementation of LISP was on IBM 704LISP 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 usedLISP has become the most widely usedprogramming language for artificial intelligenceprogramming language for artificial intelligenceand other symbolic applications.and other symbolic applications.

    LISP was standardized after a period ofLISP was standardized after a period ofdivergent evolutiondivergent evolution

  • 7/31/2019 Maclennan Chap9 Lisp

    16/90

    1616

    DESIGN: STRUCTURALDESIGN: STRUCTURAL

    ORGANIZATIONORGANIZATION

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

    Page 312Page 312

  • 7/31/2019 Maclennan Chap9 Lisp

    17/90

    1717

    Function Application Is theFunction Application Is the

    Central IdeaCentral Idea

    programming language are often dividedprogramming language are often dividedinto two classes:into two classes:Imperative languageImperative language

    Depend heavily on an assignmentDepend heavily on an assignmentstatement and a changeable memory forstatement and a changeable memory foraccomplishing a programming task.accomplishing a programming task.

    Applicative languageApplicative languageThe central idea is function application, thatThe central idea is function application, thatis, applying a function to its argument .is, applying a function to its argument .

  • 7/31/2019 Maclennan Chap9 Lisp

    18/90

    1818

    In the LISP almost everything is a functionIn the LISP almost everything is a functionapplicationapplication

    ((f a1 a2an)f a1 a2an)where f is the function and a1, a2, , an are thewhere f is the function and a1, a2, , an are the

    arguments. This notation is calledarguments. This notation is called CombridgeCombridgePolish (prefix notation).Polish (prefix notation).Example:Example:

    (plus 2 3)(plus 2 3)

    (plus 10 5 8 64)(plus 10 5 8 64)LISP isLISP is fullyfullyparenthesizedparenthesized

  • 7/31/2019 Maclennan Chap9 Lisp

    19/90

    1919

    ExampleExample

    (set Freq (make-table text nil))(set Freq (make-table text nil))is a nested function application : set isis a nested function application : set isapplied to two arguments:applied to two arguments:

    FreqFreqthe result of applying make-table to thethe result of applying make-table to thearguments text and nil.arguments text and nil.

    In an Algol-like language this would beIn an Algol-like language this would bewrittenwrittenset (Freq, make-table (text, nil))set (Freq, make-table (text, nil))

  • 7/31/2019 Maclennan Chap9 Lisp

    20/90

    2020

    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

    IfIf null(x)null(x) thenthen 00

    elseifelseif x = yx = y thenthen f(x)f(x)elseelse g(y)g(y) endifendif

  • 7/31/2019 Maclennan Chap9 Lisp

    21/90

    2121

    function definition is accomplished byfunction definition is accomplished by

    calling a function,calling a function, defundefun, with three, with three

    arguments: the name of the function,arguments: the name of the function,

    its formal parameter list, and its body.its formal parameter list, and its body.

  • 7/31/2019 Maclennan Chap9 Lisp

    22/90

    2222

    Why is everything a functionWhy is everything a functionapplication in LISP?application in LISP?

    Simplicity PrincipleSimplicity Principle

    If there is only one basic mechanism in aIf there is only one basic mechanism in alanguage, the language is easier to learn,language, the language is easier to learn,understand, and implement.understand, and implement.

  • 7/31/2019 Maclennan Chap9 Lisp

    23/90

    2323

    The List is the Primary DataThe List is the Primary Data

    Structure ConstructorStructure Constructor

    We said that one of LISPs goals was to allowWe said that one of LISPs goals was to allowcomputation with Symbolic data.computation with Symbolic data.This is accomplished by allowing the programmer toThis 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

  • 7/31/2019 Maclennan Chap9 Lisp

    24/90

    2424

    LISP manipulates list just like otherLISP manipulates list just like otherlanguages manipulate number; they canlanguages manipulate number; they canbe compared, passed to functions, putbe compared, passed to functions, puttogether, and taken apart.together, and taken apart.

  • 7/31/2019 Maclennan Chap9 Lisp

    25/90

    2525

    Programs Are Represented asPrograms Are Represented as

    ListsListsFunction 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 whosecould either be a three-element list whoseelements are the make-table, text, nil; or it couldelements are the make-table, text, nil; or it couldbe an application of the function make-table tobe an application of the function make-table tothe arguments named text and nil. Because athe 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; thatIf the list is quoted, then it is treated as data; thatis, it is unevaluated.is, it is unevaluated.

  • 7/31/2019 Maclennan Chap9 Lisp

    26/90

    2626

    If the list is quoted, then it is treated asIf the list is quoted, then it is treated asdata; 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))

    What happens?What happens?

  • 7/31/2019 Maclennan Chap9 Lisp

    27/90

    2727

    the fact that LISP represents both programsthe fact that LISP represents both programs

    and data in the same wayand data in the same way isis of the utmostof the utmostimportance:importance:

    it makes it very easy to write a LISP interpreterit makes it very easy to write a LISP interpreterin LISP.in LISP.it makes it convenient to have one LISP programit makes it convenient to have one LISP programgenerate and call for the execution of anothergenerate and call for the execution of anotherLISP program.LISP program.It also simplifies writing LISP programs thatIt also simplifies writing LISP programs thattransform and manipulate other LISP programs.transform and manipulate other LISP programs.

  • 7/31/2019 Maclennan Chap9 Lisp

    28/90

    2828

    These capabilities are important in artificialThese capabilities are important in artificialintelligence and other advanced programintelligence and other advanced program--development environmentsdevelopment environments..

    These amplification come with a reductionThese amplification come with a reductionof readabilityof readability..

  • 7/31/2019 Maclennan Chap9 Lisp

    29/90

    2929

    LISP is often InterpretedLISP is often Interpreted

    Most LISP systems provide interactive interpreters. WeMost LISP systems provide interactive interpreters. Weinteract with the LISP interpreter by typing in functioninteract with the LISP interpreter by typing in functionapplications. The LISP system then interprets them andapplications. The LISP system then interprets them andpoint out the result.point out the result.Example:Example:

    (plus 2 3)(plus 2 3)the system will respondthe system will respond55Similarly if we typeSimilarly if we type

    (eq (plus 2 3) (difference 9 4))(eq (plus 2 3) (difference 9 4))the system will respondthe system will respondtt

  • 7/31/2019 Maclennan Chap9 Lisp

    30/90

    3030

    Pure FunctionPure Function

    functions likefunctions like eqeq andandplusplus are pureare purefunctionsfunctions ((or simply functionsor simply functions)) becausebecausethey have no effect other than thethey have no effect other than the

    computation of a valuecomputation of a value..Pure functions obey the Manifest InterfacePure functions obey the Manifest InterfacePrinciple because their interfaces arePrinciple because their interfaces are

    apparentapparent ((manifestmanifest).).

    Th M if t I t f

  • 7/31/2019 Maclennan Chap9 Lisp

    31/90

    3131

    The Manifest InterfaceThe Manifest Interface

    PrinciplePrinciple

    All interfaces should beAll interfaces should be

    apparent (manifest) in theapparent (manifest) in the

    syntax.syntax.

  • 7/31/2019 Maclennan Chap9 Lisp

    32/90

    3232

    ProceduresProcedures

    Some function in LISP are pseudo-function (orSome function in LISP are pseudo-function (orprocedure). These are functions that have a sideprocedure). These are functions that have a sideeffect on the state of computer in addition toeffect on the state of computer in addition tocomputing 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 tobinds the name (atom) text to the (to be or not tobe) 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 thisThe atom n can now be used as a name for thislist in any expression, for examplelist in any expression, for example(set Freq (make-table text nil))(set Freq (make-table text nil))

  • 7/31/2019 Maclennan Chap9 Lisp

    33/90

    3333

    FunctionFunction

    another importananother importantt pseudo-function is defun,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, formaldefines a function with the name f, formalparameters x1, x2, , xn; and body bparameters x1, x2, , xn; and body bThe function application used to defineThe 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, itin LISP the binding process is dynamic, that is, ittaketakess place at run-time.place at run-time.

  • 7/31/2019 Maclennan Chap9 Lisp

    34/90

    3434

    DESIGN: DATA STRUCTUREDESIGN: DATA STRUCTURE

  • 7/31/2019 Maclennan Chap9 Lisp

    35/90

    3535

    The Primitives Include NumericThe Primitives Include Numeric

    AtomsAtoms

    We classify LISP data structure (like otherWe classify LISP data structure (like otherlanguages) intolanguages) intoprimitiveprimitive andand constructorsconstructors..The principThe principalalconstructorconstructoris the list: it permitsis the list: it permits

    more complicated structures to be built frommore complicated structures to be built fromsimpler structures.simpler structures.The primitive data structures are the startingThe primitive data structures are the startingpoints to building process. Thus, the primitivepoints to building process. Thus, the primitivess

    are those data structure that are not build fromare those data structure that are not build fromany other: they have no parts. It is for this reasonany other: they have no parts. It is for this reasonthat they are called atoms.that they are called atoms.

  • 7/31/2019 Maclennan Chap9 Lisp

    36/90

    3636

    There are at least tThere are at least twowo types of atoms intypes of atoms inall LISP systems:all LISP systems:

    NumericNumeric

    NonnumericNonnumeric

  • 7/31/2019 Maclennan Chap9 Lisp

    37/90

    3737

    LISP provides a very large set of primitiveLISP provides a very large set of primitivefunctions for manipulating numeric atoms:functions for manipulating numeric atoms:

    Arithmetic operations (plus, difference,Arithmetic operations (plus, difference,

    etc.)etc.)Predecessor and successor functionPredecessor and successor function(sub1, add1)(sub1, add1)

    Maximum and minimum functionsMaximum and minimum functionsRelation tests (equal, lessp, greaterp)Relation tests (equal, lessp, greaterp)Predicates (i.e., tests, such as zerop,Predicates (i.e., tests, such as zerop,

    onep, minusp)onep, minusp)

  • 7/31/2019 Maclennan Chap9 Lisp

    38/90

    3838

    All of these functions take both integer andAll of these functions take both integer andfloating-point (and in some systems,floating-point (and in some systems,multiple-precision) arguments and returnmultiple-precision) arguments and returnresults of the appropriate type.results of the appropriate type.

  • 7/31/2019 Maclennan Chap9 Lisp

    39/90

    3939

    ExampleExample

    LISPs use of Combridge Polish limits itsLISPs use of Combridge Polish limits itsnumerical applications.numerical applications.Example:Example:

    (-b + (b - 4ac) ) /2a(-b + (b - 4ac) ) /2amust be writtenmust 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)

  • 7/31/2019 Maclennan Chap9 Lisp

    40/90

    4040

    Nonnumeric Atoms Are AlsoNonnumeric Atoms Are Also

    ProvidedProvided

    These atoms are strings of characters thatThese atoms are strings of characters thatwere originally intended to representwere originally intended to representwords or symbols.words or symbols.

  • 7/31/2019 Maclennan Chap9 Lisp

    41/90

    4141

    ExampleExample

    With few exceptions, the only operationsWith few exceptions, the only operationsthat can be performed on nonnumericthat can be performed on nonnumericatoms are comparisions for equality andatoms are comparisions for equality and

    inequality. This is done with functioninequality. This is done with function eq:eq:Example:Example:

    ((eqeq 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,

  • 7/31/2019 Maclennan Chap9 Lisp

    42/90

    4242

    the atom nil has many uses in LISPthe atom nil has many uses in LISP.. ThisThisoperation is often used as a base foroperation is often used as a base forrecursive definitionsrecursive definitions..

    ((eq x nileq x nil))((null xnull x))

    nil is the noun and null is thenil is the noun and null is thecorresponding adjectivecorresponding adjective..

  • 7/31/2019 Maclennan Chap9 Lisp

    43/90

    4343

    Some LISP systems provide additionalSome LISP systems provide additionaltypes of atoms, such as strings. In thesetypes of atoms, such as strings. In thesecases special operations for manipulatingcases special operations for manipulatingthese values are also providedthese values are also provided

  • 7/31/2019 Maclennan Chap9 Lisp

    44/90

    4444

    Abstract Data TypeAbstract Data Type

    An abstract data type is a set of dataAn abstract data type is a set of datavalues together with a set of operationsvalues together with a set of operations

    on those values.on those values.

  • 7/31/2019 Maclennan Chap9 Lisp

    45/90

    4545

    The Principal Constructor is theThe Principal Constructor is the

    ListList

    The characteristic method of data structuringThe characteristic method of data structuringprovided by LISP is called theprovided by LISP is called the list.list.Lists are written in the S-expression notation byLists are written in the S-expression notation bysurrounding with parentheses the lists elements,surrounding with parentheses the lists elements,which are separated by blanks.which are separated by blanks.Lists can have none, one, or more elements, soLists can have none, one, or more elements, so

    they satisfy the Zero-One-Infinity Principle. Thethey satisfy the Zero-One-Infinity Principle. The

    elements of lists can themselves be lists, so theelements of lists can themselves be lists, so theZero-One-Infinity Principle is also satisfied by theZero-One-Infinity Principle is also satisfied by thenesting level of lists.nesting level of lists.

  • 7/31/2019 Maclennan Chap9 Lisp

    46/90

    4646

    The empty list, ( ) is considered equivalentThe empty list, ( ) is considered equivalentto the atomto 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 datathey are sometimes called composite datavalues.values.

  • 7/31/2019 Maclennan Chap9 Lisp

    47/90

    4747

    We caWe cann find out whether or not something is an atom byfind out whether or not something is an atom byusing 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 ( ( ) ) )nilnil

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

  • 7/31/2019 Maclennan Chap9 Lisp

    48/90

    4848

    Constructor and SelectorConstructor and Selector

    Operations that build a structure areOperations that build a structure are

    called constructors.called constructors.

    OperationOperation that extract their parts arethat extract their parts are

    called selectors.called selectors.

    C C fC d Cd A th P t f

  • 7/31/2019 Maclennan Chap9 Lisp

    49/90

    4949

    Car and Cdr Access the Parts ofCar 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 listreturns the list

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

  • 7/31/2019 Maclennan Chap9 Lisp

    50/90

    5050

    Notice that the argument to car and cdr isNotice that the argument to car and cdr isalways a nonnull listalways a nonnull list..

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

    Car and Cdr are pure functionsCar and Cdr are pure functions.. TheTheeasiest way to think of the way they workeasiest way to think of the way they workis that they make a new copy of the listis that they make a new copy of the list..

    Car and Cdr can be used inCar and Cdr can be used in

  • 7/31/2019 Maclennan Chap9 Lisp

    51/90

    5151

    Car and Cdr can be used inCar and Cdr can be used in

    combination to access thecombination to access the

    components of a listcomponents of a listExample: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)

  • 7/31/2019 Maclennan Chap9 Lisp

    52/90

    5252

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

    The composition of cars and cdrs is representedThe composition of cars and cdrs is representedby the sequence of as and ds between theby the sequence of as and ds between theinitial c and the final r.initial c and the final r.

    This can be seen more clearly if the list is writtenThis can be seen more clearly if the list is writtenas a linked data structure; then a d moves toas a linked data structure; then a d moves tothe right and an a moves down.the right and an a moves down.

  • 7/31/2019 Maclennan Chap9 Lisp

    53/90

    5353

    Figure 9.2Figure 9.2

  • 7/31/2019 Maclennan Chap9 Lisp

    54/90

    5454

    Clearly, these sequence of as and dsClearly, these sequence of as and ds

    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 ofOne solution to this is to write a set ofspecial-purpose functions for accessingspecial-purpose functions for accessing

    the part of a record. For example athe part of a record. For example afunction for accessing the hire date couldfunction for accessing the hire date couldbe defined asbe defined as

    (defun hire-date (r) (cadddr))(defun hire-date (r) (cadddr))Then (hire-date DS) returns Don SmithThen (hire-date DS) returns Don Smithhire datehire date

    I f ti C B R t dI f ti C B R t d

  • 7/31/2019 Maclennan Chap9 Lisp

    55/90

    5555

    Information Can Be RepresentedInformation Can Be Represented

    by Property Listsby Property Lists

    A personnel record wouldA personnel record would notnot probably be represented inprobably be represented inLISP in the way we have just described: it is too inflexible.LISP in the way we have just described: it is too inflexible.A better arrangement is to precede each information withA better arrangement is to precede each information withan indicator identifying the property.an indicator identifying the property.

    Example:Example:(name (Don Smith) age 45 salary 30000 hire-date(name (Don Smith) age 45 salary 30000 hire-date(august 25 1980) )(august 25 1980) )this method of representing information is called athis method of representing information is called a

    property listproperty list

    or p-list.or p-list.

    (P1 v1 P2 v2 Pn vn)(P1 v1 P2 v2 Pn vn)each Pi is the indicator for a property and each vi is theeach Pi is the indicator for a property and each vi is thecorresponding property valuecorresponding property value

    H th ti fH th ti f li tli t

  • 7/31/2019 Maclennan Chap9 Lisp

    56/90

    5656

    How can the properties of a pHow can the properties of a p--listlist

    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)

  • 7/31/2019 Maclennan Chap9 Lisp

    57/90

    5757

    What will this function do ifWhat will this function do ifwewe ask for aask for aproperty 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

  • 7/31/2019 Maclennan Chap9 Lisp

    58/90

    5858

    One way to do this is to have getpropOne way to do this is to have getprop

    return a distinguished value if thereturn a distinguished value if theproperty does not exist.property does not exist.

    An obvious choice is nil,An obvious choice is nil, but this would not be abut this would not be a good choicegood choice

    since it would then be impossible tosince it would then be impossible todistinguish an undefined property fromdistinguish an undefined property fromone that is defined but whose value isone that is defined but whose value isnil.nil.

  • 7/31/2019 Maclennan Chap9 Lisp

    59/90

    5959

    A better decision is to pick some atom,A better decision is to pick some atom,such as undefined-property, which issuch as undefined-property, which isunlikely to be used for any other purposeunlikely to be used for any other purpose..(getprop weight DS)(getprop weight DS)

    undefined-propertyundefined-property

    I f ti C B R t d iInformation Can Be Represented in

  • 7/31/2019 Maclennan Chap9 Lisp

    60/90

    6060

    Information Can Be Represented inInformation Can Be Represented inAssociation ListAssociation List

    The property list data structure works bestThe property list data structure works bestwhen exactly one value is to be associatedwhen exactly one value is to be associatedwith each property.with each property.Some properties are flags that have noSome properties are flags that have noassociated value for example retired flag in ourassociated value for example retired flag in ourpersonnel record.personnel record.if a property has several associated values, forif a property has several associated values, forexample theexample the managesmanages property, might beproperty, might beassociated with the names of everyoneassociated with the names of everyonemanaged by Don Smith.managed by Don Smith.

  • 7/31/2019 Maclennan Chap9 Lisp

    61/90

    6161

    These problems are solved by another commonThese problems are solved by another common

    LISP data structure, theLISP data structure, the association list,association list, orora-lista-list..AnAn a-lista-listis a list of pairs.is a list of pairs.

    The general form of anThe general form of an a-lista-listis a list of attribute-is a list of attribute-

    value pairs:value pairs:((a1 v1) (a2 v2)(an vn))((a1 v1) (a2 v2)(an vn))

    ( (name (Don Smith)( (name (Don Smith)

    (age 45)(age 45)(salary 30000)(salary 30000)

    (hire-date (August 25 1980)) )(hire-date (August 25 1980)) )

  • 7/31/2019 Maclennan Chap9 Lisp

    62/90

    6262

    AssocAssoc

    The function that does the forwardThe function that does the forwardassociation.association.

    For exampleFor example

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

    ReturnReturn (August 25 1980)(August 25 1980)

  • 7/31/2019 Maclennan Chap9 Lisp

    63/90

    6363

    Cons Constructs ListsCons Constructs Lists

    If the constructors undo what the selectorsIf the constructors undo what the selectorsdo and vice versa, we will have moredo and vice versa, we will have moreregular data typesregular data types..

    cons adds a new element to thecons adds a new element to thebeginning of a list.beginning of a list.

    cons is the inverse of car and cdrcons is the inverse of car and cdr

  • 7/31/2019 Maclennan Chap9 Lisp

    64/90

    6464

    Example:Example:(cons to (be or not to be))(cons to (be or not to be))

    return the listreturn 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 tobe)be)

  • 7/31/2019 Maclennan Chap9 Lisp

    65/90

    6565

    QuizQuiz::

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

  • 7/31/2019 Maclennan Chap9 Lisp

    66/90

    6666

    Notice that the second argument of consNotice that the second argument of consmust be a list.must be a list.

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

  • 7/31/2019 Maclennan Chap9 Lisp

    67/90

    6767

    ListListss Are Usually ConstructedAre Usually Constructed

    RecursivelyRecursively

  • 7/31/2019 Maclennan Chap9 Lisp

    68/90

    6868

    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

    f)f)

  • 7/31/2019 Maclennan Chap9 Lisp

    69/90

    6969

    Atoms Have PropertiesAtoms Have Properties

    LISP was originally developed for artificialLISP was originally developed for artificialintelligence application.intelligence application.

    AI applications often must deal withAI applications often must deal with the properties of objects andthe properties of objects and the relationship among objects.the relationship among objects.

  • 7/31/2019 Maclennan Chap9 Lisp

    70/90

    7070

    In LISP,In LISP, objects are represented by atoms,objects are represented by atoms, each atom has an associated p-listeach atom has an associated p-list

    represents the properties of the atom andrepresents the properties of the atom andthe relationship in which it participates.the relationship in which it participates.

  • 7/31/2019 Maclennan Chap9 Lisp

    71/90

    7171

    (set Europe (England France Spain Germany ))(set Europe (England France Spain Germany ))>> (England France Spain Germany )>> (England France Spain Germany )

    (car Europe)(car Europe)

    >> England>> England

    (eq England (car Europe))(eq England (car Europe))>> t>> t

    (eq France (car Europe))(eq France (car Europe))>> nil>> nil

    How are other properties attachedHow are other properties attached

  • 7/31/2019 Maclennan Chap9 Lisp

    72/90

    7272

    How are other properties attachedHow are other properties attachedto an atom?to an atom?

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

    ReturnReturn ParisParisWe can find out the value of a property with theWe can find out the value of a property with thegetgetfunction:function:(get France capital)(get France capital)

    ReturnReturn ParisParisFigure 9.7Figure 9.7

  • 7/31/2019 Maclennan Chap9 Lisp

    73/90

    7373

    Figure 9.7Figure 9.7

  • 7/31/2019 Maclennan Chap9 Lisp

    74/90

    7474

    Each object comes complete with aEach object comes complete with aproperty, itsproperty, itsprint name,print name, which is awhich is acharacter string tagged by pname.character string tagged by pname.

    Atoms are pointers to their propertyAtoms are pointers to their property

  • 7/31/2019 Maclennan Chap9 Lisp

    75/90

    7575

    Atoms are pointers to their propertyAtoms are pointers to their propertylistslists

    In implementation atoms are equivalent toIn implementation atoms are equivalent tomemory locationsmemory locations

    Figure 9 13Figure 9 13

  • 7/31/2019 Maclennan Chap9 Lisp

    76/90

    7676

    Figure 9.13Figure 9.13

  • 7/31/2019 Maclennan Chap9 Lisp

    77/90

    7777

    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 )

  • 7/31/2019 Maclennan Chap9 Lisp

    78/90

    7878

    Binding of atoms to functions isBinding of atoms to functions isrepresented by therepresented by the exprexprpropertyproperty

    (Get getprop expr)(Get getprop expr)

    {function expr){function expr)

    Defun equivalent to putpropDefun equivalent to putprop

    Lists Have a SimpleLists Have a Simple

  • 7/31/2019 Maclennan Chap9 Lisp

    79/90

    7979

    Lists Have a SimpleLists Have a Simple

    RepresentationRepresentation

    LISP lists are usually implemented asLISP lists are usually implemented aslinked structurelinked structure.. For instance, the listFor instance, the list

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

    is represented asis represented as a sequence of six cells in memory,a sequence of six cells in memory, each containing a pointer to the nexteach containing a pointer to the next..

    Each cell also contains a pointer to theEach cell also contains a pointer to theelement of the list it representselement of the list it represents..

  • 7/31/2019 Maclennan Chap9 Lisp

    80/90

    8080

    Figure 9.8Figure 9.8

  • 7/31/2019 Maclennan Chap9 Lisp

    81/90

    8181

    List containing other lists are representedList containing other lists are representedin 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 shownwould be represented in storage as shownin below.in below.

    Figure 9 9Figure 9.9

  • 7/31/2019 Maclennan Chap9 Lisp

    82/90

    8282

    Figure 9.9Figure 9.9

    The List Primitive Are SimpleThe List Primitive Are Simple

  • 7/31/2019 Maclennan Chap9 Lisp

    83/90

    8383

    The List Primitive Are SimpleThe List Primitive Are Simple

    and Efficientand Efficient

    CarCar

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

    CdrCdr

    D := L . rightD := L . right

  • 7/31/2019 Maclennan Chap9 Lisp

    84/90

    8484

    Figure 9.10Figure 9.10

  • 7/31/2019 Maclennan Chap9 Lisp

    85/90

    8585

    ConsCons

    new(L);new(L);

    LL .. leftleft : =: = A;A;

    LL .. rightright :=:= D;D;

    Shared sub-listsShared sub-lists

  • 7/31/2019 Maclennan Chap9 Lisp

    86/90

    8686

    Shared sub listsShared sub lists(Quiz)(Quiz)

    (set L (or not to be))(set L (or not to be))>> (or not to be)>> (or not to be)(set M (to be))(set M (to be))>> (to be)>> (to be)(cadr M)(cadr M)

    >> be>> be(set N (cons(cadr M) L))(set N (cons(cadr M) L))>>>>(car M)(car M)>>(set O(cons(car M) N))(set O(cons(car M) N))>>(cons (car M) (cons (cadr M)L))(cons (car M) (cons (cadr M)L))>>

    Sublists can be sharedSublists can be shared

  • 7/31/2019 Maclennan Chap9 Lisp

    87/90

    8787

    Sublists can be sharedSublists can be shared

    A lot of the substructures can be shared.A lot of the substructures can be shared. Memory efficiencyMemory efficiency Danger of Aliasing (and sharing of dataDanger of Aliasing (and sharing of data

    structures) only whenstructures) only whenThere is the ability to change the content ofThere is the ability to change the content of

    memorymemory

    Because car,cdr,cons are pure functions, theyBecause car,cdr,cons are pure functions, they

    have no side effect on memory, so they arehave no side effect on memory, so they aredanger freedanger free

    Li t b difi dLi t b difi d

  • 7/31/2019 Maclennan Chap9 Lisp

    88/90

    8888

    Lists can be modifiedLists can be modified

    Pseudo-functionPseudo-function rplaca : replace address partrplaca : replace address part rplacd : replace decrement partrplacd : replace decrement part

    (rplaca L A)(rplaca L A)L ^ .left := A;L ^ .left := A;

    (rplacd L D)(rplacd L D)L^ .right := D;L^ .right := D;

    Fi 9 12Fi 9 12

  • 7/31/2019 Maclennan Chap9 Lisp

    89/90

    8989

    Figure 9.12Figure 9.12(set text (to be or not to be))

    >> (to be or not to be)((rplacd (cdr text) (is all))

    Li t St t C B M difi dLi t St t C B M difi d

  • 7/31/2019 Maclennan Chap9 Lisp

    90/90

    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