Professional Documents
Culture Documents
14
ence 6 3)" evaluates to 3 and their prod- blee strill (cronk flonk))" is a four-ele- To illustrate, here follows a brief con-
uct is 27. This notation, in which each ment list whose last element is itself a versation with the genie:
operationis placed to the left of its oper- two-element list. Another short list is
ands, was invented by the Polish logi- "(plus 2 2)", illustrating the fact that — > (setq pie (plus 2 2))
cian JanLukasiewicz before computers Lisp statements themselves are lists. 4 ■
existed. Unfortunately for Lukasiewicz This is important because it means that — > (setq pi '(plus 2 2))
his name was too formidable-looking the Lisp genie, by manipulating lists (plus 2 2)
for most speakers of English, and so this and atoms, can actually construct new —>
type of notationcame to be called "Pol- wishes by itself. Hence the object of a
ish notation." Now, here is. a simple wish can be the construction—and sub- Notice the vast difference between the
problem in this notation for you, in sequent evaluation—of an entirely new values assigned to the atoms "pie" and
which you are to play the part of the wish! "pi"as aresult of thesetwo wishes asked
Lisp genie: Then there is the empty list: the list of the Lisp genie, which differ merelyin
with no elements at all. How is this writ- the presence or absence of the small but
— > (quotient 13) ten down? You might think that "()" critical single-quote mark in front of the
(plus 21 would work. Indeed, it will work, but inner list "(plus 2 2)". In the first wish,
(difference there is a second way of indicating the since there is no quote mark, that inner
23 empty list, and that is by writing "nil", "(plus 2 2)" must be evaluated. This re-
(times The two notations are synonymous, al- turns 4, which is assigned to the variable
-2 though "nil" is more commonly written "pie" as its new value. On the other
(difference 7 (plus 2 2))))) than "()". The empty list, nil, is a key hand, in the second wish, since the quote
concept of Lisp; in the universe of lists it mark is there, the list "(plus 2 2)" is nev-
Perhaps you have noticed that state- is what zero is in the universe of num- er executed as a command but is treated
ments of Lisp involve parentheses. A bers. To use another metaphor for nil, it merely as an inert lump of Lispstuff,
profusion of parentheses is one of the is like the earth in which all structures much like meat on a butcher's shelf. It is
hallmarks of Lisp. It is not uncommon are rooted. To understand what this ever so close to being "alive," yet it is
to see an expression that terminatesin a means, however, you will have to wait a dead. Therefore the value of pi in this
dozen parentheses! This makes many , bit longer. second case is the list "(plus 2 2)", a
people shudder at and yet once you fragment of Lisp code. The following
get used to their characteristic appear- >~phe most commonly exploited fea- interchange with the genie confirms the
ance Lisp expressions become remark- J- ture of an atom is that it has (or can values of these atoms:
ably intuitive, even charming, to the be given) a value. Some atoms have per-
eye, particularly when they are "pretty- manent values; others are variables. As — > pie
printed," which means that a careful in- you might expect, the value of the atom 4
dentation scheme is followed that re- "1729" is the integer 1729, and this is — > pi
veals their logical structure (as in the permanent. (I am distinguishinghere be- (plus 2 2)
preceding expression). tween the atom whose "print name" or — > (eval pi)
The heart of Lisp is its manipulable "pname" is the four-digit string "1729" 4
structures. All programs in Lisp work and the eternal Platonic essence that —>
by creating, modifying and destroying happens to be the sum of two cubes in
structures. Structures comein two types: two different ways.) The value of nil is What is this last step? I wanted to
atomic and composite, or, as they are also permanent, and it is—nil! One oth- show howyou can ask the genie to evalu-
usually called, atoms and lists. Thus cv- er atom that has itself as its permanent ate the value of an expression rather
cry Lisp object is eitheran atom or a list value is the special atom "t". than simply printing the value of that
(but not both). The onlyexceptionis the Apart from t, nil and atoms whose expression. Ordinarily the genie auto-
specialobject called "nil", which is both names are numerals, atoms are general- matically performs just one level of
an atom and a list. More about nil be- ly variables, which means that you can evaluation, but by writing "eval" you
low. What are some other typical Lisp . assign values to them and later change can get a second stage ofevaluation car-
atoms? Here are a few: their values at will. How is it done? Well, ried out. (And of course by using eval
to assign the value 4 to the atom "pie" over and over again you can continue as
hydrogen, helium, j-s-bach, 1729, pi, you can type to the Lisp genie "(setq pie long as you like.) This feature often
bar, baz, buttons-&-bows 4)". Or youcould just as well type "(setq proves invaluable, but it is a little too
pie (plus 2 2))", or even "(setq pie (plus advanced to discuss further at this stage.
Lists are theflexible datastructures of 111 1))". In any of these cases, as soon
Lisp. A list is pretty much what it sounds as you type your carriage return, pie's list except nil has at least one
like: a collection of some parts in a spe- value will become 4, and so it will re-
Every
element. This first elementis called
cific order. The parts of a list are usually main or at least until you the list's "car". Thus the car of "(eval
called its elements or members.What can perform another setq operation on the pi)" is the atom "eval". The cars of the
these members be? Well, not surprising- atom "pie". lists "(plus 2 2)", "(setq x 17)", "(eval
ly, lists can have atoms as members.Just Lisp would not be crisp if the only pi)" and "(carpi)" areall namesof oper-
as easily, however, lists can contain lists values atoms could have were numbers. ations or, as they are more commonly
as members, and those lists can in turn Fortunately an atom's value can be set called in Lisp, functions. The car of a
contain other lists as members, and so to any kind of Lisp object—any atom or list need not be the name of a func-
on recursively. Oops! I jumped the gun list whatsoever. For instance, we might tion; it need not even be an atom. For
with that word, but no harm done. You want to make thevalue of the atom "pi" instance, "((1) (2 2) (3 3 3))" is a perfect-
certainly understood what I meant, and be a list such as "(a b c)" or perhaps ly fine list. Its car is the list "(1)", whose
it will prepare you for a more technical "(plus 2 2)" instead of thenumber 4. The car in turn is not a function name but
definition of the term to come later. value belonging to an atom is often merely a numeral.
A list printed on your screen is recog- called the atom's binding, and one says Ifyou were to removea list's car, what
nizable by its parentheses. In Lisp any- the atom is bound to that value. To as- would remain? A shorter list. This is
thing bounded by matchingparentheses sign newbindings to the atoms "pie" and called the list's "cdr", a word that is spo-
constitutes a list. For instance, "(zonk "pi" we again use the "setq" operation. ken so that it sounds about halfway be-
19
tween "kidder" and "could 'er." (The
words "car" and "cdr" are relics from
the first implementation of Lisp on the
IBM 704. The letters in "car" and "cdr"
stand respectively for "contents of the
address part of register" and "contents
of the decrementpart of register." They
refer to specific hardware features of
that machine, now long since irrele-
vant.) The cdr of "(a b c)" is the list
"(b c)", whose cdr is "(c)", whose cdr is
nil. And nil has no cdr, just as it has no
car. Attempting to take the car or cdr of
nil causes (or should cause) the Lisp ge-
nie to cough out an error message, just
as attempting to divide by zero should
evoke an error message.
Here is a little table showing the cars
and cdrs of a few lists, just to make sure
the notion is unambiguous:
22
"pie". What if I had not used it? This is
what would have happened:
every 12,000 miles wish, itwill always use the value belong-
ing to that atom rather than the atom's
name. (Always? Well, almost always. I
._. you fly. shall explainin a moment. In the mean-
time look for an exception; you have
already encountered it.)
Now here are a few exercisesfor you,
some of them a bit tricky. Watch out for
the quotemarks! Onelast thing: I use the
function "reverse", which produces a
list just like its argument, only with its
elements in reverse order. For instance,
the genie, on being told "(reverse '((a b)
(c d c)))", will write "((c d c) (a b))". The
genie's lines in this dialogue are given
afterward.
(4 cdr z)
(pie cake cookie)
(cookie cake pie)
(pie)
cake
(cake cookie cake pie)
(cookie cake pie)
((reverse (cdr v)) (car v) cons)
(cake pie cookie)
r -. ..——-. __--~"T_ 1 (cookie cake pie)
The new Republic Frequent Flyer" Program: (cookie cake pie)
enroll now and begin earning yourfree round-trip travel.
last example, featuring the re-
Name
Phone: Home ( ) Business!
Company
)
Thepeated use of cons, is often called, in
Lisp slang, "consing up a list." You be-
you prefer to receive your Frequent Flyer mail at:
Do you □ Home □ Business gin with nil and then do repeated cons
operations. It is analogous to building a
"
I
Address
City - .State Zip positive integer by starting at zero and
thenperforming the successor operation
Mail to Republic Airlines Frequent FlyerProgram, Dept. SA , P.0. GA3o32s.
We'll forward your personal account numberand full information . over and over again. However, whereas
j at any stage in the latterprocess there is *.
a unique way of doing the successor op-
NOBODY SERVES OURREPUBLIC eration, given any list there are infinite-
ly many different items you might cons
""REPUBLIC V AIRLINES
onto it, thus givingrise to a vast branch-
ing tree of lists instead of the unbranch-
ing number line. It is because of this im-
24
age of a tree growing out of the ground
of nil and containing all possible lists
that I likened nil to the earth in which
all structures are rooted.
As I mentioned above, the genie does
not alwaysreplace (unquoted) atoms by but Republic gives
their values. There are cases where a
function treats its arguments, although
unquoted, as if they were quoted. Did you first class comfort
you go back and find such a case? It is
not hard. The answer is the function
"setq". In particular, in a setq command
for Just $10 over Coach.
the first atom is taken straight, not eval- (No matter howfaryou 're flyingJ
uated. As a matter of the "q" in
"setq" stands for "quote,"meaning that
the first argument is treated as if it were
quoted. Things can get tricky when you NotUnited.
learn about "set", a function similar to You pay theregular high front-cabin fare.
setq except that it does evaluate its first
argument. Hence if the value of the
atom "x" is the atom "k", then entering
"(set x 7)" will not do anything to x (its
value will remain the atom "k") but the
value of the atom "k" will now become
7. Watch closely:
NotAmerican.
— > (setq a 'b) Again, you pay a high front-cabin fare.
— > (setq
(setq b 'c)
— > (set ac)
c 'a)
— (set cb)
>
—>
Now tell me: What are the values of the
atoms "a," "b" and "c"? Here comes the
answer, so try not to peek. They are re-
spectively "a", "a"and "a". Thismaybe NotDelta.
confusing. You may be reassured to You pay a sliding scale (up to S3O over Coach) .
know that in Lisp, "set" is not very com-
monly used and such confusions do not
arise often.
(def readers-digest-condensed-version
returns a new list with 5 as its car and
whatever pi's value is as its cdr.
— > (def twice (lambda (n) (plus n n)))
(lambda (biglonglist) Such behavior is to be contrasted with The functions rdc and snoc are analo-
(cons (car biglonglist) thatof functions thatleave "side effects" gous to cdr and cons, only backward.
(cons (rac biglonglist) nil)))) in their wake. Such side effects are usu- Hence the rdc of "(a bed c)" is "(a b c
ally in the form of changed variable d)", and if you type "(snoc 5 '(1 2 3 4))",
Hence if we applythe function "readers- bindings, although thereare other possi- you will get as your answer "(12 3 4 5)".
digest-condensed-version" to the entire bilities, such as causing input or output
text of James Joyce's Finnegans Wake to take place. A typical "harmful" corn- All of this is mildly interesting so
creating it as a big long list of words), mand is a setq, and proponents of the -T\. but if you want to see the genie do
we shall obtain the shorter list "(river- "applicative"school of programming— anything truly surprising, you have to
run the)". Unfortunately reapplying the the school that says you should never allow it to make some decisions based
condensation function to this new list have any sideeffects whatever—are pro- on things that happen along the way.
will not simplify it any further. foundly disturbed by the mere mention These are sometimes called conditional
It would be nice as well as useful if of setq. For them all results must come wishes. A typical examplewould be the
we could create an inverse operation to about purely by the way functions corn- following:
readers-digest-condensed-versioncalled pute their values and hand them along
"rejoyce" that, given any two words,
would create a James Joyce novel be-
to other functions.
The only bindings the advocates of
— > (cond ((eq x 1) land)
((eq x 2) 'sea))
ginning and ending with them respec- the applicativestyle approveof are tran-
tively. Thus executionof the Lisp state- sitory "lambda bindings": those that The value returned by this statement
ment "(rejoyce 'Stately 'Yes)" would re- arise when a function is applied to its will be the atom "land" if x has thevalue
suit in the Lisp genie's generating from arguments. Whenever any function is 1, and the atom "sea" if x has the value
scratch the entire novel Ulysses. Writ- called, that function's dummy variables 2. Otherwise the value returned will be
ing this function is left as an exercise temporarily assume "lambdabindings." nil (for instance if x is 5). The atom "eg"
for the reader. These bindings are just like those result- (pronounced "eek") is the name of a
ing from a setq except that they are fleet- common Lisp function that returns the
goal that has seemed ing. That is, the moment thefunction is atom "t" (standing for "true") if its two
Onepeople some
be both desirable and
to
to
finished computing they go away, van- arguments have the same value, and nil
feasible with Lisp andrelated program- ishing without a trace. For example, in (for "no" or "false") if they do not.
ming languages is (1) to make every sin- the computation of "(rac '(a b c))" the A cond statement is a list whose car is
gle statement return value and (2) to lambdabinding of the dummy variable the function name "cond", followed by
have it be through this returned value "lyst" is to the list "(a be)", but as soon any number of cond clauses, each of
27
which is a two-elementlist. The first ele-
ment of each clause is its "condition,"
the second element is its "result." The
—> (def 6th-power
(lambda(k)
(times k (sth-powerk))))
clauses' conditions -are checked out by
the Lisp genie one by one, in order; as
soon as the genie finds a clause whose
condition is "true" (meaning that the
condition returns anything other than My question for you is this: Can you
nil) it begins calculating that clause's re- invent a definition for a .vw-parameter
sult, whose value gets returned as the function that subsumes this entire infi-
value of the entire cond statement. None nite family in one fell swoop? (Please
of the further clauses is even so much as do not write to give me your thoughts; I
glanced at! This may sound more com- know the answer andwillprovide it next
plex than it ought to. The real idea is no time.) More concretely, the question is:
more complex thansaying that the genie How would one go about defininga two-
looks for the first condition that is sat- parameter function called "power"such
isfied, then returns the corresponding that, for instance, "(power 9 3)" yields
result. 729 on being evaluated and "(power 7
Often one wants to have a catchall 4)" yields 2401? I have given you in this
clause at the end whose condition is sure column all the necessary tools to do it,
to be satisfied, so that if all other condi- provided you exercise some ingenuity.
tions fail, at least this one will be true
and the accompanying result, rather thought I would end with a news-
than nil, will be returned. It is as easy as
pie to make a condition whose value is
I break about a freshly discovered
beast: the Glazunkian porpuquine, so
non-nil; just choose it to be "t", for in- called because it is found only on the
stance, as in the following: island of Glazunkia (claimed by Upper
Bitbo, although it is just off the coast
> (cond ((eq x 1) 'land) of Burronymede). And what is a porpu-
((eq x 2) 'sea)" quine, you ask? Why, it is a strange breed
(t 'air)) of porcupine whose quills—of which,
for some reason, there are always exact-
Depending on what the value of x is, we ly nine (in Outer Glazunkia) or seven
shall get either "land", "sea" or "air" as (in Inner Glazunkia)—are smaller por-
the value of this cond, but we shall never puquines. Oho! This would certainly
get nil. Here are a few sample cond seem to be an infinite regress! But no.
statements for you to play genie to: It is just that.l forgot to mention that
there is a smallest size of porpuquine:
> (cond ((eq (eval pi) pie) the zero-inch type, which, amazingly
(eval (snoc pie pi))) enough, is totally bald of quills. Thus
(t (eval (snoc (rac pi) pi)))) quite luckily (or perhaps unluckily, de-
>. (cond ((eq 2 2) 2) ((eq 3. 3) 3)) pending on your point ofview) thatputs
> (cond (nil 'no-no-no) a stop to the threatened infinite regress.
((eq '(car nil) '(cdr nil)) Students of zoology might be inter-
'hmmm) ested to learn that the. quills on five-
(t 'yes-yes-yes)) inch porpuquines are always four-inch
porpuquines, and so on down the line.
The answers are 8, 2 and "yes-yes-yes". And students of anthropologymight be
Did you notice that "(car nil)" and (cdr equally intrigued to know that the resi-
nil)" were quoted? dents of Glazunkia (both Outer and In-
ner) utilize the nose (yes, the nose) of the
T shall close this part of the column by zero-inch porpuquine as a unit of bar-
J- displaying afamily offunction defini- ter—an odd thing to our minds, but then
tions so obvious in their pattern that you who are you and I to question the an-
would think the Lisp genie wouldsimply cient ways of the Outer and Inner Gla-
"get the hang of it" after seeing the first zunkians? Hence since a largish porpu-
few. Unfortunately. Lisp genies are frus- quine-—say a three- or a four-incher-
tratingly dense (or at least they play at has many, many such tiny noses, it is a
being dense), and they will not jump to most valuable commodity. The value of
any conclusion unless it has been spelled a porpuquine is sometimes referred to as
out explicitly for them. Look first at its "buying power," or just "power" for
the family: short. For instance, a two-incher found
in Inner Glazunkia is almost twice as
> (def square powerful as a two-incher found in Outer
(lambda (k)(times k k))) Glazunkia. Or did I get it backward?
> (defcube Anyway,, why am I telling you all
(lambda (k)(times k (squarek)))) i this? I just thought you would like
> (def 4th-power to hear about it. Anyway, who knows?
(lambda(k) (times k (cube k)))) You just might wind up visiting Glazun-
> (def sth-power kia (Inner or Outer) one of these fine
(lambda(k) days. And then all of this could come in
(times k (4th-powerk)))) mighty handy.
28