Professional Documents
Culture Documents
chp3 Lists
chp3 Lists
1. Conses
2. Equality
3. Why Lisp Has No Pointers
4. Building Lists
5. Example: Compression
6. Access
7. Mapping Functions
8. Trees
9. Understanding Recursion
10. Sets
11. Sequences
12. Stacks
13. Dotted Lists
14. Assoc Lists
15. Example: Shortest Path
16. Garbage
Notes
lists are one of the fundamental datastructure of lisp.
(but) CL is a general purpose programming language with many built in data
structures.
Often in the initial phases of programming development, a lot of lists are used.
In later versions you can switch to faster specialized data structures.
This chapter shows many things you can do with lists, and uses them to illustrate
some concepts.
1. Conses
What cons really does is combine two objects into a structure called a cons. Conses
provide a convenient representation of pairs of any type.
Conceptually a cons is a pair of pointers. One is (to) the car and the other is to
the cdr. The two halves of the cons could point to any type of object, including
conses (the latter is used to build lists)
Any non empty list can be considered as a pair of the car-value and the rest of the
list (which is either the car of a sublist or nil)
2. Equality
Each time you call cons, lisp allocates memory with room for two pointers.
If we call cons twice with the same arguments we get two values that look the same,
but not identical.
eql returns true only if the comparands are the same object
[11]> (equal l m)
T
This works for objects other than lis.
this makes both x and y point to the same structure (area of memory)
For efficiency, sometimes the lisp implementation may store a value directly, and
not a pointer. E.g small integers don't take any more space than a pointer. but in
general pointers all the way so a structure can refer to itself.
4. Building Lists
copy list takes a list and returns a copy of it with identical values but in
different conses.
(picture).
(setf y (copy-list l))
(1 2 3)
[16]> y
(1 2 3)
a list and its copy-list ed clone will be equal but never eql unless the original
list is nil.
5. Example: Compression
example:
(compress '( 1 1 1 0 1 0 0 0 0 1))
(( 3 1) 0 1 (4 0) 1)
whenever the element occurs several times in a row, those elements are replaced
with a pair the first element of which is the count and the secnod is the element.
we don't need to write (list-of ...) (make-list...) works but it has keyword
arguments which we haven't learned yet.
6. Access
Common Lisp has access functions defined in terms of car and cdr.
(nth 0 '( a b c))
A
both nth and nthcdr are zero based. Whenever you use a number to refer to the
contents of a data structure, it is zero based.
[16]> (zerop 2)
NIL
[17]> (zerop 0)
T
7. Mapping Functions
8. Trees
9. Understanding Recursion
10. Sets
11. Sequences
12. Stacks
13. Dotted Lists
14. Assoc Lists
15. Example: Shortest Path
16. Garbage