Common Lisp LISTS

  • Upload
    lalitha

  • View
    236

  • Download
    0

Embed Size (px)

Citation preview

  • 8/8/2019 Common Lisp LISTS

    1/38

    Mitthgskolan 12/6/2010 1

    Common LispCommon Lisp

    LISTSLISTS

    J.E. SpraggJ.E. Spragg

    MitthgskolanMitthgskolan

    19971997

  • 8/8/2019 Common Lisp LISTS

    2/38

    Mitthgskolan 12/6/2010 2

    ListsLists Lists are one of the fundamental dataLists are one of the fundamental data

    structures in Lisp.structures in Lisp.

    However, it is not the only data structure.However, it is not the only data structure.

    Common Lisp has moved on from beingCommon Lisp has moved on from beingmerely a LISt Processor.merely a LISt Processor.

  • 8/8/2019 Common Lisp LISTS

    3/38

    Mitthgskolan 12/6/2010 3

    ConsesConses

    What cons really does is combines two objectsWhat cons really does is combines two objects

    into a twointo a two--part object called apart object called a conscons..

    Conceptually, a cons is a pair of pointers.Conceptually, a cons is a pair of pointers.

    The first one is the car, and the second is the cdr.The first one is the car, and the second is the cdr.

    Conses provide a convenient representation forConses provide a convenient representation for

    pairs of any type.pairs of any type.

    The two halves of a cons can point to any kind ofThe two halves of a cons can point to any kind ofobject, including conses.object, including conses.

    This is the mechanism for building lists.This is the mechanism for building lists.

  • 8/8/2019 Common Lisp LISTS

    4/38

    Mitthgskolan 12/6/2010 4

    PairsPairs

    Lists in CL are defined as pairs.Lists in CL are defined as pairs.

    Any non empty list can be considered as aAny non empty list can be considered as a

    pair of the first element and the rest of thepair of the first element and the rest of thelist.list.

    We use one half of the cons to point to theWe use one half of the cons to point to the

    first element of the list, and the other tofirst element of the list, and the other topoint to the rest of the list (which is eitherpoint to the rest of the list (which is either

    another cons or nil).another cons or nil).

  • 8/8/2019 Common Lisp LISTS

    5/38

    Mitthgskolan 12/6/2010 5

    Box notationBox notation

    nil

    a

    A one element list (A)

    nil

    a b c

    A list of 3 elements (A B C)

  • 8/8/2019 Common Lisp LISTS

    6/38

    Mitthgskolan 12/6/2010 6

    What sort of list is this?What sort of list is this?

    nil

    a d

    b c

    > (setf z (list a (list b c) d))

    (A (B C) D)

  • 8/8/2019 Common Lisp LISTS

    7/38

    Mitthgskolan 12/6/2010 7

    Lists of listsLists of lists

    Given z is (A (B C) D)Given z is (A (B C) D) What value is returned here?What value is returned here?

    > (car (cdr z))> (car (cdr z))

  • 8/8/2019 Common Lisp LISTS

    8/38

    Mitthgskolan 12/6/2010 8

    ConspConsp

    The functionThe function conspconsp returns true if itsreturns true if itsargument is a cons.argument is a cons.

    So listp could be defined:So listp could be defined:

    (defun our(defun our--listp (x)listp (x)

    (or (null x) (consp x)))(or (null x) (consp x)))

    Since everything that is not a cons is anSince everything that is not a cons is an

    atom, the predicateatom, the predicate atomatom could be defined:could be defined:

    (defun out(defun out--atom (x) (not (consp x)))atom (x) (not (consp x)))

    Remember,Remember, nilnilis both anis both an atomatom and aand a listlist..

  • 8/8/2019 Common Lisp LISTS

    9/38

    Mitthgskolan 12/6/2010 9

    EqualityEquality

    Each time you call cons, Lisp allocates aEach time you call cons, Lisp allocates a

    new piece of memory with room for twonew piece of memory with room for two

    pointers.pointers. So if we call cons twice with the sameSo if we call cons twice with the same

    arguments, we get back two values that lookarguments, we get back two values that look

    the same, but are in fact distinct objects:the same, but are in fact distinct objects:> (eql (cons a nil) (cons a nil))> (eql (cons a nil) (cons a nil))

    NILNIL

  • 8/8/2019 Common Lisp LISTS

    10/38

    Mitthgskolan 12/6/2010 10

    EqualEqual

    We also need to be able to ask whether two lists have theWe also need to be able to ask whether two lists have the

    same elements.same elements.

    CL provides an equalityCL provides an equalitypredicatepredicate for this,for this, equalequal..

    eql returns true only if its arguments are the same object,eql returns true only if its arguments are the same object,

    equal, more or less, returns true if its arguments wouldequal, more or less, returns true if its arguments would

    print the same.print the same.

    > (equal (cons a nil) (cons a nil))> (equal (cons a nil) (cons a nil))

    TT

    Note: if x and y are eql, they are also equal.Note: if x and y are eql, they are also equal.

  • 8/8/2019 Common Lisp LISTS

    11/38

    Mitthgskolan 12/6/2010 11

    Why Lisp has no pointersWhy Lisp has no pointers

    One of the secrets to understanding Lisp isOne of the secrets to understanding Lisp is

    to realize that variables have values in theto realize that variables have values in the

    same way that lists have elements.same way that lists have elements.

    As conses have pointers to their elements,As conses have pointers to their elements,

    variables have pointers to their values.variables have pointers to their values.

  • 8/8/2019 Common Lisp LISTS

    12/38

    Mitthgskolan 12/6/2010 12

    Pointers to valuesPointers to values

    What happens, for example, when we setWhat happens, for example, when we set

    two variables to the same list:two variables to the same list:> (setf x (a b c))> (setf x (a b c))

    (A B C)(A B C)

    > (setf y x)> (setf y x)

    (A B C)(A B C)

  • 8/8/2019 Common Lisp LISTS

    13/38

    Mitthgskolan 12/6/2010 13

    The location in memory associated with theThe location in memory associated with the

    variable x does not contain the list itself, butvariable x does not contain the list itself, but

    a pointer to it.a pointer to it. When we assign the same value to y, LispWhen we assign the same value to y, Lisp

    copies the pointer, not the list.copies the pointer, not the list.

    Therefore, what would the value ofTherefore, what would the value of> (eql x y)> (eql x y)

    be, T or NIL? be, T or NIL?

  • 8/8/2019 Common Lisp LISTS

    14/38

    Mitthgskolan 12/6/2010 14

    Building ListsBuilding Lists

    The functionThe function copycopy--listlist takes a list andtakes a list and

    returns a copy of it.returns a copy of it.

    The new list will have the same elements,The new list will have the same elements,

    but contained in new conses.but contained in new conses.

    > (setf x (a b c)> (setf x (a b c)

    y (copyy (copy--list x))list x))

    (A B C)(A B C)

    Spend a few minutes to draw a box diagramSpend a few minutes to draw a box diagram

    of x and y to show where the pointers point.of x and y to show where the pointers point.

  • 8/8/2019 Common Lisp LISTS

    15/38

    Mitthgskolan 12/6/2010 15

    AppendAppend

    The Common Lisp functionThe Common Lisp function appendappendreturnsreturns

    the concatenation of any number of lists:the concatenation of any number of lists:

    > (append (a b) (c d) (e))> (append (a b) (c d) (e))

    (A B C D E)(A B C D E)

    AppendAppendcopies all the arguments except thecopies all the arguments except thelast.last.

  • 8/8/2019 Common Lisp LISTS

    16/38

    Mitthgskolan 12/6/2010 16

    List access functionsList access functions

    To find the element at a given position in aTo find the element at a given position in a

    list we call the functionlist we call the function nthnth..

    > (nth 0 (a b c))> (nth 0 (a b c))

    AA

    and to find theand to find the nnth cdr, we callth cdr, we call nthcdrnthcdr..

    > (nthcdr 2 (a b c))> (nthcdr 2 (a b c))

    (C)(C)

    Both nth and nthcdr are zero indexed.Both nth and nthcdr are zero indexed.

  • 8/8/2019 Common Lisp LISTS

    17/38

    Mitthgskolan 12/6/2010 17

    Zerop and LastZerop and Last

    The functionThe functionzeropzerop returns true if its argument isreturns true if its argument is

    zero.zero.

    > (zerop 0)> (zerop 0)

    TT

    The functionThe function lastlastreturns the last cons in a list.returns the last cons in a list.

    > (last (a b c))> (last (a b c))

    (C)(C) We also have:We also have:firstfirst,,secondsecond...... tenthtenth, and, and

    ccxxr, wherer, wherexx is a string of up to fouris a string of up to fouraas ors ordds.s.

  • 8/8/2019 Common Lisp LISTS

    18/38

    Mitthgskolan 12/6/2010 18

    Mapping functionsMapping functions Common Lisp provides several mappingCommon Lisp provides several mapping

    functions.functions.

    MapcarMapcaris the most frequently used.is the most frequently used.

    It takes a function and one or more lists, andIt takes a function and one or more lists, and

    returns the result of applying the function toreturns the result of applying the function toelements taken from each list, until one ofelements taken from each list, until one of

    the list runs out:the list runs out:

  • 8/8/2019 Common Lisp LISTS

    19/38

    Mitthgskolan 12/6/2010 19

    > (mapcar #(lambda (x) (+ x 10))> (mapcar #(lambda (x) (+ x 10))

    (1 2 3))(1 2 3))

    (11 12 13)(11 12 13)

    > (mapcar #list> (mapcar #list

    (a b c)(a b c)

    (1 2 3 4))(1 2 3 4))

    ((A 1) (B 2) (C 3))((A 1) (B 2) (C 3))

  • 8/8/2019 Common Lisp LISTS

    20/38

    Mitthgskolan 12/6/2010 20

    MaplistMaplist

    The related functionThe related function maplistmaplist takes the sametakes the samearguments, but calls the function onarguments, but calls the function on

    successive cdrs of the lists:successive cdrs of the lists:

    > (maplist #(lambda (x) x)> (maplist #(lambda (x) x)(a b c))(a b c))

    ((A B C) (B C) (C))((A B C) (B C) (C))

    There is alsoThere is also mapcanmapcan andand mapcmapc. Use the. Use theonon--lineline Common Lisp the LanguageCommon Lisp the Languagetoto

    discover what these mapping functions do.discover what these mapping functions do.

  • 8/8/2019 Common Lisp LISTS

    21/38

    Mitthgskolan 12/6/2010 21

    Keyword argumentsKeyword arguments

    > (member b (a b c))> (member b (a b c))

    (B C)(B C)

    MemberMemberreturns true, but instead of simplyreturns true, but instead of simply

    returningreturning tt, its returns the part of the list, its returns the part of the list

    beginning with the object it was looking for.beginning with the object it was looking for.

    By default,By default, membermembercompares objects usingcompares objects using

    eql.eql. You can override this behavior byYou can override this behavior by

    employing aemploying a keywordkeywordargument.argument.

  • 8/8/2019 Common Lisp LISTS

    22/38

    Mitthgskolan 12/6/2010 22

    An example of aAn example of a keywordkeywordargument isargument is :test.:test.

    If we pass some function as the :testIf we pass some function as the :test

    argument in a call to member, than thatargument in a call to member, than that

    function will be used to test for equalityfunction will be used to test for equalityinstead ofinstead ofeqleql..

    > (member (a) ((a) (z)) :test #equal)> (member (a) ((a) (z)) :test #equal)

    ((A) (Z))((A) (Z))

    KeywordKeywordarguments are always optional.arguments are always optional.

  • 8/8/2019 Common Lisp LISTS

    23/38

    Mitthgskolan 12/6/2010 23

    AnotherAnotherkeywordkeywordargument accepted byargument accepted by

    member is amember is a :key:key argument.argument.

    This allows you to specify a function to beThis allows you to specify a function to be

    applied to each element before comparison:applied to each element before comparison:

    > (member a ((a b) (c d)) :key #car)> (member a ((a b) (c d)) :key #car)

    ((A B) (C D))((A B) (C D))

  • 8/8/2019 Common Lisp LISTS

    24/38

    Mitthgskolan 12/6/2010 24

    MemberMember--ifif

    If we want to find an element satisfying anIf we want to find an element satisfying an

    arbitrary predicate we use the functionarbitrary predicate we use the function

    membermember--ifif::

    > (member> (member--if #oddp (2 3 4))if #oddp (2 3 4))

    (3 4)(3 4)

  • 8/8/2019 Common Lisp LISTS

    25/38

    Mitthgskolan 12/6/2010 25

    adjoinadjoin

    The functionThe function adjoinadjoin is like a conditionalis like a conditional

    conscons..

    It takes an object and a list, and conses theIt takes an object and a list, and conses the

    object onto the list only if it is not already aobject onto the list only if it is not already amember:member:

    > (adjoin b (a b c))> (adjoin b (a b c))

    (A B C)(A B C)> (adjoin z (a b c))> (adjoin z (a b c))

    (Z A B C)(Z A B C)

  • 8/8/2019 Common Lisp LISTS

    26/38

    Mitthgskolan 12/6/2010 26

    SetsSets

    CL has the functions,CL has the functions, unionunion,, intersectionintersection, and, andsetset--

    differencedifference for performing set operations on lists.for performing set operations on lists.

    These functions expect exactly two lists and alsoThese functions expect exactly two lists and alsothe samethe same keywordkeywordarguments asarguments as membermember..

    Remember, there is no notion of ordering in a set.Remember, there is no notion of ordering in a set.

    These functions wont necessarily preserve theThese functions wont necessarily preserve the

    order of the two lists.order of the two lists.

    Give me an example of a call toGive me an example of a call to unionunion. Show the. Show the

    arguments and the return value.arguments and the return value.

  • 8/8/2019 Common Lisp LISTS

    27/38

    Mitthgskolan 12/6/2010 27

    SortSort

    Common Lisp has a built in function calledCommon Lisp has a built in function calledsortsort..

    It takes a sequence and a comparison function ofIt takes a sequence and a comparison function of

    two arguments, and returns a sequence with thetwo arguments, and returns a sequence with the

    same elements, sorted according to the function:same elements, sorted according to the function:

    > (sort (0 2 1 3 8) #>)> (sort (0 2 1 3 8) #>)

    (8 3 2 1 0)(8 3 2 1 0)

    Sort is destructiveSort is destructive!!!!

    What can you do if you dont want your listWhat can you do if you dont want your list

    modified?modified?

  • 8/8/2019 Common Lisp LISTS

    28/38

    Mitthgskolan 12/6/2010 28

    Every and SomeEvery and Some

    The functionsThe functions everyevery andandsomesome take a predicate and one or moretake a predicate and one or more

    sequences.sequences.

    When given just one sequence, they test whether the elements satisfyWhen given just one sequence, they test whether the elements satisfy

    the predicate:the predicate:

    > (every #oddp (1 3 5))> (every #oddp (1 3 5))

    TT

    > (some #evenp (1 2 3))> (some #evenp (1 2 3))

    TT

    If they are given more than one sequence, the predicate must take asIf they are given more than one sequence, the predicate must take as

    many arguments as there are sequences, and arguments are drawn onemany arguments as there are sequences, and arguments are drawn one

    at a time from all the sequences:at a time from all the sequences:

    > (every #> (1 3 5) (0 2 4))> (every #> (1 3 5) (0 2 4))

    TT

  • 8/8/2019 Common Lisp LISTS

    29/38

    Mitthgskolan 12/6/2010 29

    Push and PopPush and Pop

    The representation of lists as conses makes itThe representation of lists as conses makes it

    natural to use them as pushdown stacks.natural to use them as pushdown stacks.

    This is done so often that CL provides two macrosThis is done so often that CL provides two macros

    for the purpose,for the purpose, pushpush, and, andpoppop..

    Both are defined in terms ofBoth are defined in terms ofsetfsetf..

    (push obj lst)(push obj lst)

    is the same asis the same as(setf lst (cons obj lst)(setf lst (cons obj lst)

    How canHow can poppop (pop lst) be defined?(pop lst) be defined?

  • 8/8/2019 Common Lisp LISTS

    30/38

    Mitthgskolan 12/6/2010 30

    (let ((x (car lst)))(let ((x (car lst)))

    (setf lst (cdr lst))(setf lst (cdr lst))

    x)x)

    We also have aWe also have apushnewpushnew, which is like, which is like

    pushpushbut usesbut uses adjoinadjoin instead ofinstead ofconscons..

    What difference would that make?What difference would that make?

  • 8/8/2019 Common Lisp LISTS

    31/38

    Mitthgskolan 12/6/2010 31

    Dotted ListsDotted Lists

    The kind of lists that can be built by callingThe kind of lists that can be built by calling

    listlistare more precisely known asare more precisely known asproperproper

    listslists..

    A proper list is eitherA proper list is eithernilnil, or a, or a conscons whosewhose

    cdrcdris a proper list.is a proper list.

    However, conses are not just for buildingHowever, conses are not just for building

    lists.lists.

    Whenever you need a structure with twoWhenever you need a structure with two

    fields you can use a cons.fields you can use a cons.

  • 8/8/2019 Common Lisp LISTS

    32/38

    Mitthgskolan 12/6/2010 32

    You will be able to useYou will be able to use carcarto refer to theto refer to the

    first field andfirst field and cdrcdrto refer to the second.to refer to the second.

    > (setf pair (cons a b))> (setf pair (cons a b))

    (A . B)(A . B)

    Because this cons is not a proper list, it isBecause this cons is not a proper list, it is

    displayed in dot notation.displayed in dot notation.

    In dot notation the car and cdr of each consIn dot notation the car and cdr of each cons

    are shown separated by a period.are shown separated by a period.

  • 8/8/2019 Common Lisp LISTS

    33/38

    Mitthgskolan 12/6/2010 33

    A cons that isnt a proper list is called aA cons that isnt a proper list is called a

    dotted list.dotted list.

    However, remember that a dotted list isntHowever, remember that a dotted list isnt

    really a list at all.really a list at all.

    It is a just a two part data structure.It is a just a two part data structure.

    a b

    (A . B)

  • 8/8/2019 Common Lisp LISTS

    34/38

    Mitthgskolan 12/6/2010 34

    AssocAssoc--listslists

    It is natural to use conses to representIt is natural to use conses to represent

    mappings.mappings.

    A list of conses is called anA list of conses is called an assocassoc--listlistoror

    alistalist..

    Such a list could represent a set ofSuch a list could represent a set of

    translations, for example:translations, for example:> (setf languages ((lisp . easy) (C . hard)> (setf languages ((lisp . easy) (C . hard)

    (Pascal . good) (Ada . bad))(Pascal . good) (Ada . bad))

  • 8/8/2019 Common Lisp LISTS

    35/38

    Mitthgskolan 12/6/2010 35

    AssocAssoc--lists are slow, but convenient whenlists are slow, but convenient whenengaged in rapid prototyping.engaged in rapid prototyping.

    Common Lisp has a built in function,Common Lisp has a built in function, assocassoc, for, for

    retrieving the pair associated with a given key:retrieving the pair associated with a given key:

    > (assoc C languages)> (assoc C languages)

    (C . HARD)(C . HARD)

    > (assoc Smalltalk languages)> (assoc Smalltalk languages)

    NILNIL

    LikeLike membermember,, assocassoc takestakes keywordkeywordarguments,arguments,

    includingincluding :test:test andand :key.:key.

  • 8/8/2019 Common Lisp LISTS

    36/38

    Mitthgskolan 12/6/2010 36

    Garbage CollectionGarbage Collection

    Automatic memory management is one of Lisps most valuable features.Automatic memory management is one of Lisps most valuable features.

    A Lisp system maintains a segment of memory called theA Lisp system maintains a segment of memory called the heapheap.. The system keeps track of unused memory in the heap and allocates it toThe system keeps track of unused memory in the heap and allocates it to

    new objects.new objects.

    Allocating memory from the heap is sometimes known asAllocating memory from the heap is sometimes known as consingconsing..

    If such memory was never freed, Lisp would quickly run out of heapIf such memory was never freed, Lisp would quickly run out of heap

    space.space. So the Lisp system periodically searches through the heap, looking forSo the Lisp system periodically searches through the heap, looking for

    memory that is no longer needed and can be reclaimed.memory that is no longer needed and can be reclaimed.

    This is calledThis is calledgarbagegarbage, and the scavenging operation is called, and the scavenging operation is calledgarbagegarbage

    collectioncollection, GC., GC.

  • 8/8/2019 Common Lisp LISTS

    37/38

    Mitthgskolan 12/6/2010 37

    An ExampleAn Example

    Search is one of the basic problem solvingSearch is one of the basic problem solving

    strategies in artificial intelligencestrategies in artificial intelligence

    programming.programming.

    Lets look at an example of breadthLets look at an example of breadth--firstfirst

    search.search.

  • 8/8/2019 Common Lisp LISTS

    38/38

    Mitthgskolan 12/6/2010 38

    NetworkNetwork

    A

    B

    C

    D

    (setf network ((A B C) (B C) (C D)))