This action might not be possible to undo. Are you sure you want to continue?
The Little Schemer
F o u r t h E d i t i o n
Daniel P Friedman and Matthias Felleisen
Foreord bf G J. s
The Ten Commandments
The First Commandment
When recurring on a list of atoms, /at, ak
two questions about it: [au//? /at) and else.
When recurring on a number, a, ak two
questions about it: [ten? a) and else.
When recurring on a list of
S
expressions, /,
ak three question about it: [au//?/), [atam?
[ car /)), and else.
The Second Commandment
Use cons to build lists.
The Third Commandment
The Fifh Commandment
When building a value with + ,always use
0 for the value of the terminating line, for
adding 0 does not change the value of an
addition.
When building a value with x, always use
1 for the value of the terminating line, for
multiplying by 1 does not change the value
of a multiplication.
When building a value with LÜÏÛ_ always
consider [) for the value of the terminating
line.
When building a list, describe the frst typi The Sixth Commandment
cal element, and then ceas it onto the natu
ral recursion.
The Fourth Commandment
Always change at leat one argument while
recurring. When recurring on a list of atoms,
/at,use [cdr /at). When recurring on a num
ber, a,use [su/1 a). And when recurring on
a list of
S
expressions, /,use [car/)and [cdr
/)if neither [au//? I) nor [atam? [car/)) are
true.
It must be changed to be closer to termina
tion. The changing argument must be tested
in the termination condition:
when using cdr, test termination with au//?
and
when using su/1, test termination with
ten?.
S
implify only ater the function is correct.
The Seventh Commandment
Recur on the su/pars that are of the same
nature:
• On the sublists of a list.
• On the subexpressions of an arithmetic
expression.
The Eighth Commandment
Use help functions to abstract from represen
tations.
The Ninth Commandment
Abstract common patterns with a new func
tion.
The Tenth Commandment
Build functions to collect more than one
value at a time.
The Five Rules
The Law of Car
The primitive car is defned only for non
empty lists.
The Law of Cdr
The primitive cdr is defned only for non
empty lists. The cdrof any nonempty list
is always another list.
The Law of Cons
The primitive caas takes two arguments.
The second argument to ceasmust be a list.
The result is a list.
The Law of Null?
The primitive au//?is defned only for lists.
The Law of Eq?
The primitive eq' takes two arguments.
Ea must be a nonnumeric atom.
The Little Schemer
Fourth Edition
Daniel P. Friedman
Indiana Uni1ersity
Bloomington, Indiana
Matthias Felleisen
Rice Uni1ersity
Houston, Texas
Ür8wÍBgS by Üu8B0 ÜÍbby
ÎOr8wOrd by Û8r8Íd J. buSSm8B
The MIT Press
Cabridge, Masahusetts
London, England
Original edition published as The Little LISPer. © 1986, 1974 by Scientifc Research
Associates.
First MIT Press Edition, 1987.
© 1996 Massachusetts Institute of Technology
All rights reserved. No part of this book may be reproduced in any form by any
electronic or mechanical means (including photocopying, recording, or information
storage and retrieval) without permission in writing from the publisher.
This book was set by the authors and was printed and bound in the United States
of America.
Library of Congress CataloginginPublication Data
Fiedman, Daniel P.
The little schemer / Daniel P. Fiedman and Matthias Felleisen; drawings by
Duane Bibby; foreword by Gerald J. Sussman. 4 ed. , 1st MIT Press ed.
p. em.
Rev. ed. of: The little LISPer. 3rd ed. @1989.
Includes index.
ISBN 0262560992 (pbk: alk. paper)
1. Scheme ( Computer program language) 2. LISP ( Computer program language)
I. Felleisen, Matthias. II. Fiedman, Daniel P. Little LISPer. III. Title.
QA76. 73. S34F75 1996
005. 13'3dc20
9539853
CIP
To Mar, Helga, and our childrn
( (Contents)
(Foreword ix)
(Preface xi)
((
1
. Toys) 2)
((2. Do It, Do It Again, and Again, and Again ... ) 14)
((3. Cons the Magnifcent) 32)
((4. Numbers Games) 58
)
((5. *Oh My Gawd*: It's Fll of Stars) 80)
((6. Shadows) 96)
((7. Fiends and Relations) 110)
((8. Lambda the Ultimate) 124)
((9 .... and Again, and Again, and Again, ... ) 148)
((
10. What Is the Value of All of This?) 174)
(Intermission 192)
(Index 194))
IOrCVOrd
This foreword appeared in the second and third editions of The Li ttle
LISPer. We reprint it here with the permission of the author.
In 1967 I took an introductory course in photography. Most of the students (including me) came
into that course hoping to learn how to be creativeto take pictures like the ones I admired
by artists such a Edward Weston. On the frst day the teacher patiently explained the long
list of technical skills that he wa going to teach us during the term. A key was Ansel Adams'
"Zone System" for previsualizing the print values (blackness in the fnal print) in a photograph
and how they derive from the light intensities in the scene. In support of this skill we had
to learn the use of exposure meters to measure light intensities and the use of exposure time
and development time to control the black level and the contrast in the image. This is in turn
supported by even lower level skills such as loading flm, developing and printing, and mixing
chemicals. One must learn to ritualize the process of developing sensitive material so that one
gets consistent results over many years of work. The frst laboratory session was devoted to
fnding out that developer feels slippery and that fxer smells awful.
But what about creative composition? In order to be creative one must frst gain control
of the medium. One can not even begin to think about organizing a great photograph without
having the skills to make it happen. In engineering, as in other creative arts, we must learn
to do analysis to support our eforts in synthesis. One cannot build a beautiful and functional
bridge without a knowledge of steel and dirt and considerable mathematical technique for using
this knowledge to compute the properties of structures. Similarly, one cannot build a beautiful
computer system without a deep understanding of how to "previsualize" the process generated
by the procedures one writes.
Some photographers choose to use blackandwhite 8x10 plates while others choose 35mm
slides. Each has its advantages and disadvantages. Like photography, programming requires a
choice of medium. Lisp is the medium of choice for people who enjoy free style and fexibility.
Lisp was initially conceived as a theoretical vehicle for recursion theory and for symbolic
algebra. It has developed into a uniquely powerful and fexible family of software development
tools, providing wraparound support for the rapidprototyping of software systems. As with
other languages, Lisp provides the glue for using a vat library of canned parts, produced
by members of the user community. In Lisp, procedures are frstclass data, to be passed as
arguments, returned a values, and stored in data structures. This fexibility is valuable, but
most importantly, it provides mechanisms for formalizing, naming, and saving the idiomsthe
common patterns of usage that are essential to engineering design. In addition, Lisp programs
can easily manipulate the representations of Lisp programsa feature that has encouraged the
development of a vast structure of program synthesis and analysis tools, such as crossreferencers.
The Little LISPer is a unique approach to developing the skills underlying creative program
ming in Lisp. It painlessly packages, with considerable wit , much of the drill and practice that
is necessary to learn the skills of constructing recursive processes and manipulating recursive
datastructures. For the student of Lisp programming, The Li ttle LISPer can perform the same
service that Hanon' s fnger exercises or Czerny' s piano studies perform for the student of piano.
Foreword
Gerald J. Sussman
Cambridge, Massachusetts
ix
ÏrC!BCC
To celebrate the twentieth anniversary of Scheme we revised The Little LISPer a
third time, gave it the more accurate title The Little Schemer, and wrote a sequel :
The Seasoned Schemer.
Programs accept data and produce data. Designing a program requires a thorough understand
ing of data; a good program refects the shape of the data it deals with. Most collections of data,
and hence most programs, are recursive. Recursion is the act of defning an object or solving a
problem in terms of itself.
The goal of this book is to teach the rader to think rcursively. Our frst task is to decide
which language to use to communicate this concept . There are three obvious choices: a natural
language, such a English; formal mathematics; or a programming language. Natural languages
are ambiguous, imprecise, and sometimes awkwardly verbose. These are all virtues for general
communication, but something of a drawback for communicating concisely as precise a concept
a recursion. The language of mathematics is the opposite of natural language: it can express
powerful formal ideas with only a few symbols. Unfortunately, the language of mathematics
is often cryptic and barely accessible without special training. The marriage of technology
and mathematics presents us with a third, almost ideal choice: a programming language. We
believe that programming languages are the best way to convey the concept of recursion. They
share with mathematics the ability to give a formal meaning to a set of symbols. But unlike
mathematics, programming languages can be directly experiencedyou can take the programs in
this book, observe their behavior, modify them, and experience the efect of these modifcations.
Perhaps the best programming language for teaching recursion i s Scheme. Scheme i s
inherently symbolicthe programmer does not have to think about the relationship between the
symbols of his own language and the representations in the computer. Recursion is Scheme' s nat
ural computational mechanism; the primary programming activity is the creation of (potentially)
recursive defnitions. Scheme implementations are predominantly interactivethe programmer
can immediately participate in and observe the behavior of his programs. And, perhaps most
importantly for our lessons at the end of this book, there is a direct correspondence between
the structure of Scheme programs and the data those programs manipulate.
Although Scheme can be described quite formally, understanding Scheme does not require
a particularly mathematical inclination. In fact , The Little Schemer is based on lecture notes
fom a twoweek "quickie" introduction to Scheme for students with no previous programming
experience and an admitted dislike for anything mathematical . Many of these students were
preparing for careers in public afairs. It is our belief that writing prgrams rcursively in Scheme
is essentially simple patter rcognition. Since our only concern is recursive programming, our
treatment is limited to the whys and wherefores of just a few Scheme features: car, cdr, cons,
eq?, null ?, zero? , addl, subl, number?, and, or, quote, lambda, defne, and cond. Indeed, our
language is an idealized Scheme.
The Little Schemer and The Seasoned Schemer will not introduce you to the practical
world of programming, but a mastery of the concepts in these books provides a start toward
understanding the nature of computation.
Preface xi
What You Need to Know to Read This Book
The reader must be comfortable reading English, recognizing numbers, and counting.
Acknowledgments
We are indebted to many people for their contributions and assistance throughout the devel
opment of the second and third editions of this book. We thank Bruce Duba, Kent Dybvig,
Chris Haynes, Eugene Kohlbecker, Richard Salter, George Springer, Mitch Wand, and David S.
Wise for countless discussions that infuenced our thinking while conceiving this book. Ghasan
Abbas, Charles Baker, David Boyer, Mike Dunn, Terry Falkenberg, Rob Fiedman, John Gateley,
Mayer Goldberg, Iqbal Khan, Julia Lawall, Jon Mendelsohn, John Nienart , Jefrey D. Perotti,
Ed Robertson, Anne Shpuntof, Erich Smythe, Guy Steele, Todd Stein, and Larry Weisselberg
provided many important comments on the drafts of the book. We especially want to thank Bob
Filman for being such a thorough and uncompromising critic through several readings. Finally
we wish to acknowledge Nancy Garrett, Peg Fletcher, and Bob Filman for contributing to the
design and 'ery.
The fourth and latest edition greatly benefted from Dorai Sitaram' s incredibly clever Scheme
typesetting program SLTE. Kent Dybvig' s Chez Scheme made programming in Scheme a
most pleasant experience. We gratefully acknowledge criticisms and suggestions from Shelaswau
Bushnell, Richard Cobbe, David Combs, Peter Drake, Kent Dybvig, Rob Fiedman, Steve Ganz,
Chris Haynes, Erik Hilsdale, Eugene Kohlbecker, Shriram Krishnamurthi, Julia Lawall, Suzanne
Menzel Collin McCurdy, John Nienart , Jon Rossie, Jonathan Sobel , George Springer, Guy Steele,
John David Stone, Vikram Subramaniam, Mitch Wand, and Melissa WingardPhillips.
Guidelines for the Reader
Do not rush through this book. Read carefully; valuable hints are scattered throughout the
text. Do not read the book in fewer than three sittings. Read systematically. If you do not flly
understand one chapter, you will understand the next one even less. The questions are ordered
by increasing difculty; it will be hard to answer later ones if you cannot solve the earlier ones.
The book is a dialogue between you and us about interesting examples of Scheme programs.
If you can, try the examples while you read. Schemes are readily available. While there are
minor syntactic variations between diferent implementations of Scheme (primarily the spelling of
particular names and the domain of specifc functions) , Scheme is basically the same throughout
the world. To work with Scheme, you will need to defne atom?, subl, and addl. which we
introduced in The Little Schemer:
(define atom?
(labda (x)
(and (not (pair? x)) (not (null? x)))))
To fnd out whether your Scheme has the correct defnition of atom?, try (atom? (quote ()))
and make sure it returns #f. In fact , the material is also suited for modern Lisps such Ü
Common Lisp. To work with Lisp, you will also have to add the function atom?:
xii
(defun atom? (x)
(not (listp x)))
Preface
Moreover, you may need to modify the programs slightly. Typically, the material requires
only a few changes. Suggestions about how to try the programs in the book are provided in
the framenotes. Famenotes preceded by "S: " concern Scheme, those by "L:" concern Common
Lisp.
In chapter 4 we develop basic arithmetic from three operators: add1 , sub1 , and zero ?. Since
Scheme does not provide add1 and sub1 , you must defne them using the builtin primitives for
addition and subtraction. Therefore, to avoid a circularity, our basic arithmetic addition and
subtration must be written using diferent symbols: ÷ and , respectively.
We do not give any formal defnitions in this book. We believe that you can form your
own defnitions and will thus remember them and understand them better than if we had
written eah one for you. But be sure you know and understand the Laws and Commandments
thoroughly before passing them by. The key to learning Scheme is "pattern recognition. " The
Commandments point out the patterns that you will have already seen. Early in the book,
some concepts are narrowed for simplicity; later, they are expanded and qualifed. You should
also know that , while everything in the book is Scheme, Scheme itself is more general and
incorporates more than we could intelligibly cover in an introductory text . After you have
mastered this book, you can read and understand more advanced and comprehensive books on
Scheme.
We use a few notational conventions throughout the text , primarily changes in typeface
for diferent classes of symbols. Variables and the names of primitive operations are in i talic.
Baic data, including numbers and representations of truth and falsehood, is set in sans serif.
Keywords, i. e. , defne, lambda, cond, else, and, or, and quote, are in boldface. When you
try the programs, you may ignore the typefaces but not the related framenotes. To highlight
this role of typefaces, the programs in framenotes are set in a typewriter face. The typeface
distinctions can be safely ignored until chapter 10, where we treat programs as data.
Finally, Webster defnes "punctuation" as the act of punctuating; specifcally, the act ,
pratice, or system of using standardized marks in writing and printing to separate sentences
or sentence elements or to make the meaning clearer. We have taken this defnition literally
and have abandoned some familiar uses of punctuation in order to make the meaning clearer.
Specifcally, we have dropped the use of punctuation in the lefthand column whenever the item
that precedes such punctuation is a term in our programming language.
Food appears in many of our examples for two reasons. First , food is easier to visualize
than abstract symbols. (This is not a good book to read while dieting. ) We hope the choice of
food will help you understand the examples and concepts we use. Second, we want to provide
you with a little distraction. We know how frustrating the subject matter can be, and a little
distraction will help you keep your sanity.
You are now ready to start . Good luck! We hope you will enjoy the challenges waiting for
you on the following pages.
Preface
Bon appetit !
Daniel P. Fiedman
Matthias Felleisen
xiii
The Little Schemer
Is it true that this is an atom?
atom1
1 L, S: (quote atom) or 'atom
"L: " and "S:" are described in the preface.
Is it true that this is an atom?
turkey
Is it true that this is an atom?
I4ò2
Is it true that this is an atom?
u
Is it true that this is an atom?
•abc$
Is it true that this is a list?
(atom)1
1 L, S: (quote (atom) ) or ' ( atom)
Is it true that this is a list?
(atom turkey or)
Toys
Yes,
because atom i s a string of characters
beginning with the letter a .
Yes,
because turkey is a string of characters
beginning with a letter.
Yes,
because I4ò2i s a string of digits.
Yes,
because u i s a string of one character,
which is a letter.
Yes,
because •abc$ i s a string of characters
beginning with a letter or special character
other than a left ¯( or right ¯)
parenthesis.
Yes,
because (atom) i s an atom enclosed by
parentheses.
Yes,
because it is a collection of atoms enclosed
by parentheses.
3
Is it true that this is a list?
(atom turkey) or
Is it true that this is a list?
( (atom turkey) or)
Is it true that this is an Sexpression?
xyz
Is it true that this is an Sexpression?
(x y z)
Is it true that this is an Sexpression?
((x y) z)
Is it true that this is a list?
(how are you doing so far)
How many Sexpressions are in the list
(how are you doi ng so far)
and what are they?
Is it true that this is a list?
( ( ( how) are) ( (you) (doing so) ) far)
How many Sexpressions are in the list
( ( ( how) are) ( (you) (doi ng so) ) far)
and what are they?
4
No,
because these are actually two
Sexpressions not enclosed by parentheses.
The frst one is a list containing two
atoms, and the second one is an atom.
Yes,
because the two Sexpressions are now
enclosed by parentheses.
Yes,
because all atoms ae Sexpressions.
Yes,
because it is a list .
Yes,
because all lists are Sexpressions.
Yes,
because i t i s a collection of Sexpressions
enclosed by parentheses.
Six,
how, are, you, doi ng, so, and far.
Yes,
because i t i s a collection of Sexpressions
enclosed by parentheses.
Three,
( ( how) are) , ( (you) (doi ng so) ) , and far.
Chapter 1
Is it true that this is a list?
(
¹
Yes,
because it contains zero Sexpressions
enclosed by parentheses. This special
Sexpression is called the null (or empty)
list .
Is it true that this is an atom? No,
()
Is it true that this is a list?
(() () () ( ) )
What i s the LÚÍ of l
where l is the argument
(a b c)
What is the LÚÍ of l
where
l is ((a b c) x y z)
What is the LÚÍ of l
where l is hotdog
What is the LÚÍ of l
where l is ()
Toys
because ( ) is j ust a list .
Yes,
a,
because it is a collection of Sexpressions
enclosed by parentheses.
because a is the frst atom of this list .
(a b c) ,
because (a b c) i s the frst Sexpression of
this nonempty list .
No answer.
You cannot ak for the LÚÍ of an atom.
No answer. 1
You cannot ak for the LÚÍ of the empty
list .
1 L: nil
The Law of Car
The primitive car is defned
only for nonempty lists.
5
What is the car of l
where
l is ( ( ( hotdogs) ) (and) ( pi ckl e) rel i sh)
What is ( car l)
where
l is ( ( ( hotdogs) ) (and) ( pi ckl e) rel i sh)
What is ( car ( car l))
where
l is ( ( ( hotdogs) ) (and) )
What i s the cdr of l
where
l is (a b c)
Note: "cdr" is pronounced "coulder. "
What is the cdr of l
where
l is ((a b c) x y z)
What is the cdr of l
where
l is ( hamburger)
What is ( cdr l)
where
l is ( (x) t r)
What is ( cdr a)
where
a is hotdogs
6
( ( hotdogs) ) ,
read a:
"The list of the list of hotdogs. "
( ( hotdogs) ) is the frst Sexpression of l .
( ( hotdogs) ) ,
because ( car l) is another way to ak for
"the car of the list l. "
( hotdogs) .
(b c) ,
because (b c) is the list l without ( car l ) .
(x y z) .
( ) .
(t r) ,
because ( cdr l) is just another way to ak
for "the cdr of the list l . "
No answer.
You cannot ak for the cdr of an atom.
Chapter 1
What is ( cdr l)
where l is ¸)
No answer. 1
You cannot ask for the cdr of the null list .
1 L: nÍ1
The Law of Cdr
The primitive cdr is defned only for
nonempty lists. The cdr of any non
empty list is always another list.
What is ( car ( cdr l ))
where
l is ( ( b) (x y) ((L)))
What is ( cdr ( cdr l ))
where
l is ( ( b) (x y) ((L)))
What is ( cdr ( car l ))
where
l is (a (b (L))d)
What does car take a an argument?
What does cdr take as an argument?
What is the cons of the atom a and the list l
where a is peanut
and
l is ( butter and jel l y)
This can also be written "( cons a l )" .
Read: "cons the atom a onto the list l. "
Toys
(x y) ,
because ((x y) ((L)))is ( cdr l), and (x y) is
the car of ( cdr l ) .
(((L)))ç
because ((x y) ((L))) is ( cdr l ) , and (((L)))
is the cdr of ( cdr l ) .
No answer,
since ( car l) is an atom, and cdr does not
take an atom as an argument; see The Law
of Cdr.
It takes any nonempty list .
It takes any nonempty list .
( peanut butter and jel l y) ,
because cons adds an atom to the front of
a list .
7
What is the LÛ7b of b and l
where b is ( banana and)
and
l is (peanut butter and jel l y)
What is ¸ LÛ7b b l)
where
b is ( ( hel p) thi s)
and
l is (is very ( ( hard) to l earn) )
What does LÛ7b take a its arguments?
What is ¸ LÛ7b b l)
where
s is (a b (c))
and
l is ( )
What is ¸ LÛ7b b l)
where b is a
and l is ( )
What is ¸ LÛ7b b l)
where
b is ((a b L))
and
l is b
What is ¸ LÛ7b b l)
where b is a
and l is b
8
( (banana and) peanut butter and jel l y) ,
because LÛ7b adds any Sexprssion to the
front of a list.
( ( (hel p) thi s) is very ( ( hard) to l earn) ) .
LÛ7b takes two arguments:
the frst one is any Sexpression;
the second one is any list .
((a b ¸L)))¿
because () is a list .
(a) .
No answer, 1
since the second argument l must be a list .
1 In practice, (cona a /) works for all values a and /, and
(ca (cona a /)) =a
(cd (cona a /)} = /.
No answer.
Why?
Chapter 1
The Law of Cons
The primitive cons taes two arguments.
The second argument to cons must be a
list. The result is a list.
What is ( cons s ( car l ) )
where s is a
and
l is ((b) c d)
What i s ( cons s ( CJ r l ) )
where s is a
and
l is ((b) c d)
Is i t true that the list l i s the null list
where l is ( )
What is ( null ?1 (quote ( ) ) )
1 L! 0u11
Is ( null? l) true or false
where
l is (a b c)
Toys
¸a b) .
Why?
¸a c d) .
Why?
Yes,
because it i s the list composed of zero
Sexpressions.
This question can also be written:
( null ? l ) .
Tue,
because (quote ( ) )
1
is a notation for the
null list .
1 L! Also 0 and • ().
S: Also •().
False,
because l is a nonempty list .
9
Is ( null ? a) true or false
where
a is spaghetti
No answer/
because you cannot ask null? of Ü atom.
1 In practice, (null? a) is false for everything, except the
empty list.
The Law of Null?
The primitive null ? is de
fned only for lists.
Is it true or false that b is an atom
where b is Harry
Is ( atom ?
1
b) true or false
where
b is Harry
1
L: (defu atom? (x)
(not (listp x) ) )
S: (define atom?
(labda (x)
(and (not (pair? x)) (not (null? x) ) ) ) )
Is ( atom? b) true or false
where
ö is (Harry had a heap of appl es)
How many arguments does atom? take and
what are they?
10
Tue,
because Harry is a string of characters
beginning with a letter.
Tue,
because ( atom? b) is j ust another way to
ak "Is b is an atom?"
False,
since ö is a list.
It takes one argument. The argument can be
any Sexpression.
Chapter 1
Is ( atom? ( car l ) ) true or false
where
l is (Harry had a heap of appl es)
Is ( atom? ( cdr l)) true or false
where
l is (Harry had a heap of apples)
Is ( atom? ( cdr l)) true or false
where
l is (Harry)
Is ( atom? ( car ( cdr l ) ) ) true or false
where
l is (swi ng low sweet cherry oat)
Is ( atom? ( car ( cdr l ) ) ) true or false
where
l is (swi ng (l ow sweet) cherry oat)
Tue or false: a1 and a2 are the same atom
where a1 is Harry
and
a2 is Harry
Is ( eq?1 a1 a2) true or false
where a1 is Harry
and
a2 is Harry
1 L: eq
Is ( eq? a1 a2) true or flse
where a1 is margari ne
and
a2 is butter
Toy
Tue,
because ( car l) is Harry, and Harry is an
atom.
False.
False,
because the list ( ) is not an atom.
Tue,
because ( cdr l) is (l ow sweet cherry oat ) ,
and ( car ( cdr l )) i s l ow, which i s an atom.
False,
since ( cdr l) is ( ( l ow sweet) cherry oat ) , and
( car ( cdr l ) ) is (l ow sweet) , which is a list .
Tue,
because a1 is the atom Harry and a2 is the
atom Harry.
Tue,
because ( eq? a1 a2) is j ust another way to
ak, "Are a1 and a2 the same
nonnumeric atom?"
False,
since a1 and a2 are diferent atoms.
1 1
How many arguments does eq? take and
what are they?
Is ( eq? l1 l2) true or false
where l1 is ¸ )
and
l2 is (strawberry)
Is ( eq? n1 n2) true or false
where n1 is 6
and
n2 is 7
It takes two arguments. Both of them must
be nonnumeric atoms.
No answer, 1
¸ ) and (strawberry) are lists.
1 In pratice, lists m8 be arguments 0Í egT. Tw lists are
egT if they are the same list.
No answer, 1
6 and 7 are numbers.
1 In pratice, some numbers may be arguments 0f egT.
The Law of Eq?
The primitive eq? takes two ar
guments. Each must be a non
numeric atom.
Tue,
Is ( eq? ( LÚr l) Ú) true or false
where
l is (Mary had a l i ttl e l amb chop)
and
because ( LÚr l) is the atom Mary, and the
argument Ú is also the atom Mary.
Ú is Mary
Is ( eq? ( cdr l) Ú) true or false
where
l is (soured mi l k)
and
Ú is mi l k
12
No answer.
See The Laws of Eq? and Cdr.
Chapter 1
Is ( eq? ( car l) ( car ( cdr l ) ) ) true or false
where
l is ( beans beans we need jel l y beans)
Tue,
because it compares the frst and second
atoms in the list .
=Now go make yourself a peanut butter and jelly sandwich. ¢
This space reserved for
JÏÏÏY b¯AÏÏbÎ
13
�))�
�m��m�
�
�
�� �
���
Tue or false: ( lat ? l)
where
l is (Jack Sprat could eat no chi cken fat)
Tue or false: ( lat ? l)
where
l is ( (Jack) Sprat coul d eat no chi cken fat)
Tue or false: ( lat? l)
where
l is (Jack (Sprat coul d) eat no chi cken fat)
Tue or false: ( lat ? l)
where l is ( )
Tue or false: a lat i s a list of atoms.
Write the function lat ? using some, but not
necessarily all , of the following functions:
car cdr Lonb null ? atom? and eq?
Tue,
because each Sexpression in l is an atom.
False,
since ( car l) is a list .
False,
since one of the Sexpressions in l is a list.
Tue,
because it does not contain a list .
Tue!
Every lat is a list of atoms!
You were not expected to be able to do this
yet , because you are still missing some
ingredients. Go on to the next question.
Good luck.
Are jOU rested?
Do It, Do It Again, and Again, and Again . . . 15
(defne lat ?1
(lambda ( l )
(cond
( ( null ? l) #t )
( ( atom? ( car l ) ) ( lat ? ( cdr l ) ) )
(else #f ) ) ) )
What i s the value of ( lat ? l )
where
l is the argument ( bacon and eggs)
1 L: (defu 1at? (1}
(cond
( (null 1} t}
( (atom? (ca 1} } (lat? (cdr 1} } }
( t nil} } }
How do we determine the answer #t for the
application
( lat ? l)
What is the frst question asked by ( lat ? l)
What is the meaning of the cond¯line
( (null ? l) #t )
where
l is ( bacon and eggs)
What is the next question?
16
#t .
The application ( lat ? l)
where
l is ( bacon and eggs)
has the value #t truebecause l is a lat .
You were not expected to know this one
either. The answer is determined by
answering the questions asked by lat
Hint: Write down the defnition of the
function lat ? and refer to it for the next
group of questions.
( null? l)
Note:
( cond . . . ) asks questions;
(lambda . . . ) creates a function; and
(defne . . . ) gives it a name.
( null ? l) asks if the argument l is the null
list. If it is, the value of the application is
true. If it is not , we ask the next question.
In this case, l is not the null list, so we ask
the next question.
( atom? ( car l ) ) .
Chapter 2
What is the meaning of the line
( ( atom? ( car l ) ) ( lat? ( cdr l ) ) )
where
l is (bacon and eggs)
What is the meaning of
( lat? ( cdr l ))
Now what i s the argument l for lat ?
What is the next question?
What is the meaning of the line
( ( null? l) #t )
where
l is now (and eggs)
What is the next question?
What is the meaning of the line
( ( atom? ( car l ) ) ( lat? ( cdr l ) ) )
where
l is (and eggs)
What is the meaning of
( lat ? ( cdr l ) )
Do It, Do It Again, and Again, and Again . . .
( atom? ( car l ) ) asks if the frst Sexpression
of the list l is an atom. If ( car l) is an atom,
we want to know if the rest of l is also
composed only of atoms. If ( car l) is not an
atom, we ask the next question. In this case,
( car l) is an atom, so the value of the
function is the value of ( lat ? ( cdr l ) ) .
( lat ? ( cdr l ) ) fnds out i f the rest of the list l
is composed only of atoms, by referring to
the function with a new argument .
Now the argument l is ( cdr l ) , which is
(and eggs) .
( null ? l ) .
( null ? l) asks i f the argument l i s the null
list . If it is, the value of the application is
#t . If it is not , we ask the next question. In
this case, l is not the null list , so we ask the
next question.
( atom? ( car l ) ) .
( atom? ( car l ) ) asks i f ( car l) i s an atom. If
it is an atom, the value of the application is
( lat ? ( cdr l ) ) . If not , we ask the next
question. In this case, ( car l) is an atom, so
we want to fnd out if the rest of the list l is
composed only of atoms.
( lat ? ( cdr l)) fnds out if the rest of l is
composed only of atoms, by referring again
to the function lat ?, but this time, with the
argument ( cdr l ) , which is (eggs) .
17
What is the next question?
What is the meaning of the line
( ( null ? l) #t )
where
l is now (eggs)
What is the next question?
What is the meaning of the line
( ( atom? ( car l ) ) ( lat ? ( cdr l ) ) )
where
l is now (eggs)
What is the meaning of ( lat ? ( cdr l ) )
Now, what i s the argument for lat ?
What is the meaning of the line
( ( null ? l) #t )
where
l is now ( )
Do you remember the question about
( lat ? l)
18
( null ? l ) .
( null ? l) asks i f the argument l i s the null
list . If it is, the value of the application is
#t true. If it is not, move to the next
question. In this cae, l is not null, so we ask
the next question.
( atom? ( car l ) ) .
( atom? ( car l )) asks i f ( car l) i s an atom. If
it is, the value of the application is
( lat ? ( cdr l ) ) . If ( car l) is not an atom, ak
the next question. In this case, ( car l) is an
atom, so once again we look at ( lat? ( cdr l ) ) .
( lat ? ( cdr l ) ) fnds out i f the rest of the list l
is composed only of atoms, by referring to
the function lat ?, with l becoming the value
of ( cdr l ) .
( ) .
( null ? l) asks if the argument l is the null
list . If it is, the value of the application is
the value of #t . If not , we ak the next
question. In this case, () is the null list. So,
the value of the application ( lat ? l)
where
l is ( bacon and eggs) , is #t true.
Probably not . The application ( lat? l) has
the value #t if the list l is a list of atoms
where
l is ( bacon and eggs) .
Chapter 2
Can you describe what the function lat ? does
in your own words?
This is the function lat ? again:
(defne lat ?
(lambda ( l )
(cond
( ( null ? l) #t )
( ( atom? ( car l )) ( lat ? ( cdr l ) ) )
(else #f))))
What is the value of ( lat? l)
where
l is now ( bacon (and eggs))
What is the frst question?
What is the meaning of the line
( ( null? l) #t )
where
l is ( bacon (and eggs))
What is the next question?
What is the meaning of the line
( ( atom? ( car l )) ( lat ? ( cdr l ) ) )
where
l is ( bacon (and eggs))
Do It, Do It Again, and Again, and Again ...
Here are our words:
"lat ? looks at each Sexpression in a list , in
turn, and asks if each Sexpression is an
atom, until it runs out of Sexpressions. If
it runs out without encountering a list , the
value is #t . If it fnds a list , the value is
#ffalse. "
To see how we could arrive at a value of
"false, " consider the next few questions.
#f,
since the list l contains an Sexpression
that is a list .
( null ? l ) .
( null ? l) asks i f l is the null list . If i t i s, the
value is #t . If l is not null, move to the next
question. In this case, it is not null, so we
ask the next question.
( atom? ( car l ) ) .
( atom? ( car l )) asks i f ( car l) i s an atom. If
it is, the value is ( lat ? ( cdr l ) ) . If it is not ,
we ask the next question. In this case,
( car l) is an atom, so we want to check if the
rest of the list l is composed only of atoms.
19
What is the meaning of
( lat ? ( cdr l ) )
What i s the meaning of the line
( ( null ? l) #t )
where
l is now ((and eggs) )
What i s the next question?
What is the meaning of the line
( ( atom? ( car l ) ) ( lat ? ( cdr l ) ) )
where
l is now ( (and eggs) )
What i s the next question?
What is the meaning of the question else
Is else true?
else
Why is else the last question?
Why do we not need to ask any more
questions?
What is the meaning of the line
(else #f )
20
( lat ? ( cdr l ) ) checks to see if the rest of the
list l is composed only of atoms, by referring
to lat ? with l replaced by ( cdr l ) .
( null ? l) asks i f l i s the null list. If i t i s null,
the value is #t . If it is not null , we ask the
next question. In this case, l is not null , so
move to the next question.
( atom? ( car l ) ) .
( atom? ( car l )) asks i f ( car l) i s an atom. If
it is, the value is ( lat ? ( cdr l ) ) . If it is not ,
we move to the next question. In this case,
( car l) is not an atom, so we ask the next
question.
else.
else asks if else is true.
Yes, because the question else is always true!
Of course.
Because we do not need to ask any more
questions.
Because a list can be empty, can have an
atom in the frst position, or can have a list
in the frst position.
else asks if else is true. If else is truea it
always isthen the answer is #ffalse.
Chapter 2
What is
) ) )
Can you describe how we determined the
value #f for
( lat? l)
where
l is ( bacon (and eggs) )
Is (oÏ ( null ? ll ) ( atom? l2) ) true or false
where l1 is ¸ )
and
l2 is (d e f g)
Is (oÏ ( null ? l1 ) ( null ? l2) ) true or false
where
l1 is (a b c)
and
l2 is ¸ )
Is ¸LÏ ( null ? l1 } ( null ? l2) ) true or false
where
l1 is (a b c)
and
l2 is (atom)
What does ¸LÏ ) do?
Do It, Do It Agan, and Again, and Again . ..
These are the closing or matching
parentheses of ( cond . . . , (lambda . . . , and
(defne . . . , which appear at the beginning
of a function defnition.
Here is one way to say it :
"( lat? l) looks at each item in its argument
to see if it is an atom. If it runs out of
items before it fnds a list , the value of
( lat ? l) is #t . If it fnds a list , as it did in
the example ( bacon (and eggs) ) , the value
of ( lat ? l) is #f. "
Tue,
because ( null ? l1 ) is true where l1 is ( ) .
Tue,
because ( null ? l2) is true where l2 is ( ) .
False,
because neither ( null? l1 ) nor ( null? l2) is
true where
l1 is (a b c)
and
l2 is (atom) .
(oÏ . . . ) aks two questions, one at a time. If
the frst one is true it stops and answers true.
Otherwise it asks the second question and
answers with whatever the second question
answers.
21
Is it true or false that a is a member of lat
where a is tea
and
lat is (coffee tea or mi l k)
Is ( member? a lat) true or false
where a is poached
and
lat is (fri ed eggs and scrambl ed eggs)
This is the function member?
(defne member?
(lambda (a lat)
(LLÏd
( ( null ? lat) #f )
(else ¸LÏ ( eq? ( car lat) a)
( member? a ( cdr lat) ) ) ) ) ) )
What i s the value of ( member? a lat)
where a is meat
and
lat is ( mashed potatoes and meat gravy)
How do we determine the value #t for the
above application?
What is the frst question asked by
( member? a lat)
22
Tue,
because one of the atoms of the lat,
(cofee tea or mi l k)
i s the same as the atom atea.
False,
since a is not one of the atoms of the lat.
#t ,
because the atom meat is one of the atoms
of lat ,
( mashed potatoes and meat gravy) .
The value is determined by asking the
questions about ( member? a lat ) .
Hint : Write down the defnition of the
function member? and refer to it while you
work on the next group of questions.
( null ? lat ) .
This i s also the frst question asked by lat ?.
Chapter 2
The First Commandment
(preliminary)
Always ask null ? as the frst question in expressing
any function.
What is the meaning of the line
( ( null ? lat) #f )
where
lat is (mashed potatoes and meat gravy)
What is the next question?
Why is else the next question?
Is else really a question?
What is the meaning of the line
(else ¸LÏ ( eq? ( car lat) a)
( member? a ( cdr lat ) ) ) )
Tue or false:
¸LÏ ( eq? ( car lat) a)
( member? a ( cdr lat) ) )
where a i s meat
and
lat is (mashed potatoes and meat gravy)
Do It, Do It Again, and Again, and Again . . .
( null ? lat) asks if lat is the null list . If it is,
the value is #f, since the atom meat was not
found in lat. If not , we ask the next question.
In this case, it is not null, so we ak the next
question.
else.
Because we do not need to ask any more
questions.
Yes, else is a question whose value is always
true.
Now that we know that lat is not null ?, we
have to fnd out whether the car of lat is the
same atom as a, or whether a is somewhere
in the rest of lat. The answer
¸LÏ ( eq? ( car lat) a)
( member? a ( cdr lat ) ) )
does this.
We will fnd out by looking at each question
in turn.
23
Is ( eq? ( car lat) a) true or false
where a is meat
and
lat is ( mashed potatoes and meat gravy)
What is the second question of ¸LÏ )
Now what are the arguments of member?
What is the next question?
Is ( null ? lat) true or false
where
lat is (potatoes and meat gravy)
What do we do now?
What is the next question?
What is the meaning of
¸LÏ ( eq? ( car lat) a)
( member? a ( cdr lat ) ) )
Is a eq? to the car of lat
24
False,
because meat is not eq? to mashed,
the car of
( mashed potatoes and meat gravy) .
( member? a ( cdr lat ) ) .
This refers t o the function with the
argument lat replaced by ( cdr lat ) .
a i s meat
and
lat is now ( cdr lat) , specifcally
( potatoes and meat gravy) .
( null ? lat ) .
Remember The First Commandment.
#ffalse.
Ask the next question.
else.
¸LÏ ( eq? ( car lat) a)
( member? a ( cdr lat) ) )
fnds out i f a i s eq? to the car of lat or i f a is
a member of the cdr of lat by referring to the
function.
No, because a is meat and the car of lat is
potatoes.
Chapter 2
So what do we do next?
Now, what are the arguments of member?
What is the next question?
What do we do now?
What is the next question?
What is the vlue of
¸LÏ ( eq? ( car lat) a)
( member? a ( cdr lat) ) )
Why?
What do we do now?
We ask ( member? a ( cdr lat ) ) .
a i s meat, and
lat is (and meat gravy) .
( null ? lat ) .
Ask the next question, since ( null ? lat) is
false.
else.
The value of ( member? a ( cdr lat ) ) .
Because ( eq? ( car lat) a) i s false.
Recurrefer to the function with new
arguments.
What are the new arguments? a is meat, and
lat is ( meat gravy) .
What is the next question? ( null ? lat ) .
What do we do now? Since ( null ? lat) is false, ask the next
question.
What is the next question? else.
Do It, Do It Agan, and Again, and Again . . . 25
What is the value of
¸LÏ ( eq? ( car lat) a)
( �e�ber? a ( cdr lat ) ) )
What i s the value of the application
( �e�ber? a lat )
where a is meat
and
lat is ( meat gravy)
What is the value of the application
( �e�ber? a lat)
where a is meat
and
lat is (and meat gravy)
What is the value of the application
( �e�ber? a lat)
where a is meat
and
lat is ( potatoes and meat gravy)
What is the value of the application
¸�e�ber? a lat )
where a is meat
and
lat is ( mashed potatoes and meat gravy)
Just to make sure you have it right , let ' s
quickly run through it again. What is the
value of ( �e�ber? a lat)
where
a is meat
and
lat is ( mashed potatoes and meat gravy)
¸ null ? lat )
26
#t ,
because ( car lat ) , which is meat, and a,
which is meat , are the same atom.
Therefore, ¸LÏ ) answers with #t .
#t ,
because we have found that meat is a
member of
( meat gravy) .
#t ,
because meat is also a member of the lat
(and meat gravy) .
#t ,
because meat is also a member of the lat
( potatoes and meat gravy).
#t ,
because meat is also a member of the lat
( mashed potatoes and meat gravy).
Of course, this is our original lat.
#t.
Hint : Write down the defnition of the
function �e�ber? and its arguments and
refer to them as you go through the next
group of questions.
No. Move to the next line.
Chapter 2
else
Yes.
¸LÏ ( eq? ( car lat) a)
Perhaps.
( member? a ( cdr lat) ) )
( eq? ( car lat) a) No. Ask the next question.
What next?
Recur with a and ( cdr lat)
where a is meat
and
( cdr lat) is ( potatoes and meat gravy) .
( null ? lat) No. Move to the next line.
else Yes, but ( eq? ( car lat) a) is false.
Recur with a and ( cdr lat)
where a is meat
and
( cdr lat) is (and meat gravy) .
( null ? lat) No. Move to the next line.
else Yes, but ( eq? ( car lat) a) is false.
Recur with a and ( cdr lat)
where a is meat
and
( cdr lat) is ( meat gravy) .
( null ? lat) No. Move to the next line.
( eq? ( car lat) a) Yes, the value is #t .
Do It, Do It Again, and Again, and Again . . . 27
¸LÏ ( eqP ( car lat) a)
( memberP a ( cdr lat) ) )
What i s the value of ( memberP a lat)
where a is meat
and
lat is ( meat gravy)
What is the value of ( memberP a lat)
where a is meat
and
lat is (and meat gravy)
What is the value of ( member? a lat)
where a is meat
and
lat is ( potatoes and meat gravy)
What is the value of ( memberP a lat)
where a is meat
and
lat is (mashed potatoes and meat gravy)
What is the value of ( memberP a lat)
where a is l i ver
and
lat is ( bagels and lox)
Let ' s work out why it is #f. What ' s the frst
question member? asks?
( null ? lat)
28
#t .
#t .
#t .
#t .
#t .
#f.
(7Ull ? lat) .
No. Move t o the next line.
Chapter 2
else
( null ? lat)
else
( null ? lat)
else
( null ? lat)
What is the value of ( member? a lat)
where a is l i ver
and
lat is ( )
What i s the value of
¸LÏ ( eq? ( car lat) a)
( member? a ( cdr lat) ) )
where
a is l i ver
and
lat is ( l ox)
Do It, Do It Again, and Again, and Again . . .
Yes, but ( eq? ( car lat) a) is false.
Recur with a and ( cdr lat)
where a is l i ver
and
( cdr lat) is (and l ox) .
No. Move to the next line.
Yes, but ( eq? ( car lat) a) is false.
Recur with a and ( cdr lat)
where a is l i ver
and
( cdr lat) is (l ox) .
No. Move to the next line.
Yes, but ( eq? ( car lat) a) is still false.
Recur with a and ( cdr lat)
where a is l i ver
and
( cdr lat) is ¸ ) .
Yes.
#f.
#f.
29
What is the value of ( member? a lat)
where a is l i ver
and
lat is (l ox)
What is the value of
¸LÏ ( eq? ( car lat) a)
( member? a ( cdr lat) ) )
where
a is l i ver
and
lat is (and lox)
What is the value of ( member? a lat)
where a is l i ver
and
lat is (and l ox)
What is the value of
¸LÏ ( eq? ( car lat) a)
( member? a ( cdr lat ) ) )
where
a is l i ver
and
lat is ( bagel s and lox)
What is the value of ( member? a lat)
where a is l i ver
and
lat is ( bagel s and l ox)
30
#f.
#f.
#f.
#f.
#f.
Chapter 2
Do you believe all this? Then you may rest!
This space for doodling
Do It, Do It Agan, and Again, and Again . . . 31
What is ( rmber a lat)
where a is mi nt
and
lat is ( l amb chops and mi nt jelly)
( rmber a lat)
where a is mi nt
and
lat is ( l amb chops and
mi nt fl avored mi nt jel l y)
( rmber a lat)
where a is toast
and
lat is ( bacon l ettuce and tomato)
( rmber a lat)
where a is cup
and
lat is (coffee cup tea cup and hi ck cup)
What does ( rmber a lat) do?
What steps should we use to do this?
And if ( null ? lat) is true?
What do we know if ( null ? lat) is not true?
Is there any other question we should ask
about the lat?
Cons the Magifcent
( l amb chops and jel l y)
"Rember" stands for rmove a member.
( l amb chops and fl avored mi nt jel l y) .
(bacon lettuce and tomato) .
(coffee tea cup and hi ck cup) .
It takes an atom and a lat as i ts arguments,
and makes a new lat with the frst occurrence
of the atom in the old lat removed.
First we will test ( null ? lat)The First
Commandment .
Return ¸ ) .
We know that there must be at least one
atom in the lat .
No. Either a lat is empty or it contains at
least one atom.
33
What do we do if we know that the lat
contains at least one atom?
How do we ask questions?
How do we ak if a is the same as ( car lat )
What would be t he value of ( rmber a lat ) if
a were the same as ( car lat )
What do we do i f a i s not the same a
( car lat )
How do we remove the frst occurrence of a
in the rest of lat
Is there any other question we should ak?
Now, let ' s write down what we have so far:
(defne rmber
(lambda (a lat)
(cond
( ( null ? lat ) (quote ( )))
(else (Cond
( ( eq? ( car lat) a) ( cdr lat ))
(else ( rmber a
( cdr lat ))))))))
What is the value of ( rember a lat ) where
a is bacon
and
lat is ( bacon l ettuce and tomato)
34
We ak whether a is equal to ( car lat ).
By using
(Cond
(

(
( eq? ( car lat ) a).
( cdr lat ).

)
 )) .
We want to keep ( car lat ), but also fnd out
if a is somewhere in the rest of the lat .
( rmber a ( cdr lat )).
No.
( l ettuce and tomato) .
Hint : Write down the function rmber and
its arguments, and refer to them as you go
through the next sequence of questions.
Chapter 3
Now, let ' s see if this function works. What is
the frst question?
What do we do now?
else
What next?
( eq? ( car lat) a)
Is this the correct value?
But did we really use a good example?
What does rmber do?
What do we do now?
What is the value of ¸rmber a lat)
where a is and
and
lat is ( bacon l ettuce and tomato)
Cons the Magnifcent
( null ? lat) .
Move t o the next line and ask the next
question.
Yes.
Ask the next question.
Yes, so the value is ( cdr lat) . In this case, it
is the list
( l ettuce and tomato) .
Yes, because it is the original list without the
atom bacon.
Who knows? But the proof of the pudding is
in the eating, so let ' s try another example.
It takes an atom and a lat as its arguments,
and makes a new lat with the frst occurrence
of the atom in the old lat removed.
We compare each atom of the lat with the
atom a, and if the comparison fails we build
a list that begins with the atom we j ust
compared.
( bacon l ettuce tomato) .
35
Let us see if our function rmber works.
What is the frst question asked by rmber
What do we do now?
else
( eq? ( car lat) a)
What is the meaning of
(else ( rmber a ( cdr lat ) ) )
( null ? lat)
else
( eq? ( car lat) a)
What is the meaning of
( rmber a ( cdr lat) )
( null ? lat)
else
36
( null ? lat ) .
Move to the next line, and ask the next
question.
Okay, so ask the next question.
No, so move to the next line.
else asks if else is truea it always isand
the rest of the line says to recur with a and
( cdr lat) , where
a is and
and
( cdr lat) is (l ettuce and tomato) .
No, so move to the next line.
Sure.
No, so move to the next line.
Recur
where
a is and
and
( cdr lat) is (and tomato) .
No, so move to the next line, and ask the
next question.
Of course.
Chapter 3
( eq? ( car lat) a)
So what is the result?
Is this correct?
What did we do wrong?
How can we keep from losing the atoms
bacon and l ettuce
Yes.
( cdr l at)(tomato) .
No, since (tomato) is not the list
( bacon l ettuce and tomato)
with j ust aandremoved.
We dropped and, but we also lost all the
atoms preceding and.
We use Cons the Magnifcent . Remember
cons , from chapter 1?
The Second Commandment
Use cons to build lists.
Let 's see what happens when we use cons
(defne rmber
(lambda (a lat)
(Cond
( ( n·ull? lat) (quote ( ) ) )
(else (cond
(( eq? ( car lat) a) ( cdr lat) )
(else ( cons ( car lat)
( rmber a
( cdr lat) ) ) ) ) ) ) ) )
What i s the value of ( rmber a lat)
where a is and
and
lat is (bacon l ettuce and tomato)
Cons the Magnifcent
( bacon l ettuce tomato) .
Hint : Make a copy of this function with
cons and the arguments a and lat so you
can refer to it for the following questions.
37
What is the frst question?
What do we do now?
else
( eq? ( car lat) a)
What is the meaning of
( cons ( car lat)
( rmber a
( cdr lat ) ) )
where
a is and
and
lat is ( bacon l ettuce and tomato)
What is the meaning of ( rmber a ( cdr lat) )
( null ? lat)
else
( eq? ( car lat) a)
What is the meaning of
( cons ( car lat)
( rmber a
( cdr lat ) ) )
38
( null ? lat ) .
Ask the next question.
Yes, of course.
No, so move to the next line.
It says to cons the car of latbacononto
the value of
( rmber a ( cdr lat ) ) .
But since we don' t know the value of
( rmber a ( cdr lat) ) yet , we must fnd it
before we can cons ( car lat) onto it.
This refers to the function with lat replaced
by ( cdr lat)( l ettuce and tomato) .
No, so move to the next line.
Yes, ask the next question.
No, so move to the next line.
It says to cons the car of latl ettuceonto
the value of
( rmber a ( cdr lat ) ) .
But since we don' t know the value of
( rmber a ( cdr lat) ) yet , we must fnd it
before we can cons ( car lat) onto it .
Chapter 3
What is the meaning of ( rmber a ( cdr lat ) )
( null ? lat)
else
( eq? ( car lat) a)
What is the value of the line
( ( eq? ( car lat) a) ( cdr lat) )
Are we fnished?
We now have a value for
( rmber a ( cdr lat) )
where a i s and
and
( cdr lat) is (and tomato)
This value is (tomato)
What next?
What is the result when we cons l ettuce onto
(tomato)
What does (l ettuce tomato) represent?
Cons the Magifcent
This refers to the function with lat replaced
by ( cdr lat ) , that is, (and tomato) .
No, so ask the next question.
Still .
Yes.
( cdr lat)(tomato ) .
Certainly not ! We know what ( rmber a lat )
is when lat is (and tomato) , but we don' t yet
know what it is when lat is
( l ettuce and tomato)
or
( bacon l ettuce and tomato) .
Recall that we wanted to cons l ettuce onto
the value of ( rmber a ( cdr lat ) )
where
a was and and ( cdr lat ) was (and tomato) .
Now that we have this value, which is
(tomato) , we can cons l ettuce onto it .
( l ettuce tomato) .
It represents the value of
( cons ( car lat )
( rember a
( cdr lat ) ) ) ,
when
lat is ( l ettuce and tomato)
and
( rmber a ( cdr lat ) ) is (tomato) .
39
Are we fnished yet?
We now have a value for ( rmber a ( cdr lat) )
where a i s and
and
( cdr lat) is ( l ettuce and tomato)
This value is ( l ettuce tomato)
This is not the fnal value, so what must we
do again?
What is the result when we cons bacon onto
( l ettuce tomato)
What does ( bacon l ettuce tomato) represent?t
t Lunch?
Are we fnished yet?
Can you put in your own words how we
determined the fnal value
( bacon l ettuce tomato)
40
Not quite. So far we know what
( rmber a lat) is when
lat is ( l ettuce and tomato) ,
but we don' t yet know what i t i s when
lat is ( bacon lettuce and tomato) .
Recall that , at one time, we wanted to cons
bacon onto the value of ( rmber a ( cdr lat) ) ,
where
a wa and
and
( cdr lat) was ( l ettuce and tomato) .
Now that we have this value, which is
( l ettuce tomato) ,
we can cons bacon onto it.
( bacon l ettuce tomato) .
It represents the value of
( cons ( car lat)
( rmber a ( cdr lat ) ) ) ,
when
lat is ( bacon l ettuce and tomato)
and
( rmber a ( cdr lat) ) is ( l ettuce tomato) .
Yes.
In our words:
"The function rmber checked each atom of
the lat , one at a time, to see if it was the
same as the atom and. If the car was not
the same as the atom, we saved it to be
consed to the fnal value later. When
rmber found the atom and, it dropped it,
and consed the previous atoms back onto
the rest of the lat. "
Chapter 3
Can you rewrite rmber so that it refects the
above description?
Do you think this is simpler?
So why don' t we simplify right away?
Let' s see if the new rmber is the same a the
old one. What is the value of the application
( rmber a lat)
where a is and
and
lat is ( bacon l ettuce and tomato)
( null ? lat)
( eq? ( car lat) a)
else
What is the meaning of
( cons ( car lat)
( rmber a ( cdr lat) ) )
Cons the Magifcent
Yes, we can simplify it.
(defÏe rmber
(lambda ( a lat)
(LoÏd
( ( null ? lat) (quote ( ) ) )
( ( eq? ( car lat) a) ( cdr lat ) )
(elÜe ( cons ( car lat)
( rmber a ( cdr lat ) ) ) ) ) ) )
Fnctions like rmber can always be
simplifed in this manner.
Because then a function' s structure does not
coincide with its argument ' s structure.
( bacon l ettuce tomato) .
Hint : Write down the function rmber and
its arguments and refer to them as you go
through the next sequence of questions.
No.
No.
Yes, so the value is
( cons ( car lat)
( rmber a ( cdr lat ) ) ) .
This says t o refer t o the function rmber but
with the argument lat replaced by ( cdr lat) ,
and that after we arrive at a value for
( rmber a ( cdr lat) ) we must cons
( car lat )bacon¨nto it.
41
( null ? lat)
( eq? ( car lat ) a)
else
What is the meaning of
( cons ( car lat)
( rember a ( cdr lat ) ) )
( null ? lat)
( eq? ( car lat) a)
What is the value of the line
( ( eq? ( car lat) a) ( cdr lat) )
Now what?
Now what?
Now that we have completed rmber
try this example: ( rmber a lat)
where a is sauce
and
lat is (soy sauce and tomato sauce)
42
No.
No.
Yes, so the value is
( cons ( car lat)
( rmber a ( cdr lat ) ) ) .
This says we recur using the function
rmber, with the argument lat replaced by
( cdr lat) , and that after we arrive at a value
for ( rmber a ( cdr lat) ) , we must cons
( car lat )l ettuceonto it.
No.
Yes.
It is ( cdr lat)(tomato) .
Now cons ( car lat)l ettuceonto (tomato) .
Now cons ( car lat )bacononto
( l ettuce tomato) .
( rmber a lat) is (soy and tomato sauce) .
Chapter 3
What is (frsts l)
where
l is ( (appl e peach pumpki n)
(pl um pear cherry)
(grape raisi n pea)
( bean carrot eggpl ant))
What is (frsts l)
where
l is ( ( a b) (c d) (e f) )
What is (frsts l)
where l is ¸ )
What i s (frsts l)
where
l is ( (five pl ums)
(four)
(el even green oranges))
What is (frsts l)
where
l is ( ( (five pl ums) four)
(el even green oranges)
( ( no) more) )
In your own words, what does (frsts l ) do?
Cons the Magnifcent
( appl e pl um grape bean) .
(a c e) .
( ) .
(fi ve four el even) .
( (fi ve pl ums) el even (no) ) .
We tried the following:
"The function frsts takes one argument , a
list, which is either a null list or contains
only nonempty lists. It builds another list
composed of the frst Sexpression of each
internal list . "
43
See if you can write the function frsts
Remember the Commandments!
Why
(defne frsts
(lambda ( l )
. . . ) )
Why (cond . . . )
Why ( ( null ? l) . . . )
Why (else
Why (else
Why ( cons
Why (frsts ( cdr l ) )
Why ) ) )
44
This much is easy:
(defne frsts
(lambda ( l )
(cond
( ( null ? l) . . . )
(else ( cons . . . (frsts ( cdr l ) ) ) ) ) ) )
Because we always state the function name,
(lambda, and the argument¸s) of the
function .
Because we need to ak questions about the
actual arguments.
The First Commandment.
Because we only have two questions to ak
about the list l: either it is the null list , or it
contains at least one nonempty list.
See above. And because the last question is
always else.
Because we are building a listThe Second
Commandment .
Because we can only look at one Sexpression
at a time. To look at the rest, we must recur.
Because these are the matching parentheses
for ( cond, (lambda, and (defne, and they
always appear at the end of a function
defnition.
Chapter 3
Keeping in mind the defnition of (frsts l)
what is a typical element of the value
of (frsts l)
where
l is ( ( a b) ¸L d) ¸e f) )
What is another typical element?
Consider the function seconds
What would be a typical element of the value
of ( seconds l)
where
l is ¸ ¸a b) ¸L d) ¸e f) )
How do we describe a typical element for
(frsts l)
When we fnd a typical element of (frsts l)
what do we do with it?
a.
L¿ or even e.
b, d, or f.
As the car of an element of l( car ( car l ) ) .
See chapter 1 .
cons i t onto the recursion(frsts ( cdr l ) ) .
The Third Commandment
When building a list, describe the frst typical ele
ment, and then cons it onto the natural recursion.
With The Third Commandment , we can now
fll in more of the function frsts
What does the last line look like now?
Cons the Magifcent
(else ( cons ( car ( car l ) ) (frsts ( cdr l ) ) ) ) .
~~
typical
element
natural
recursion
45
What does (frsts l) do
(defne frsts
(lambda ( l )
(cond
( ( null ? l) . . . )
( else ( cons ( car ( car l ))
(frsts ( cdr l ) ) ) ) ) ) )
where l is ¸ ¸Ü b) ¸L d) ¸e f) )
( null ? l) where l is ¸ ¸Ü b) ¸L d) ¸e f) )
What is the meaning of
( cons ( car ( car l))
(frsts ( cdr l)))
( null ? l) where l is ¸ ¸L d) ¸e f) )
What is the meaning of
( cons ( car ( car l ) )
(frsts ( cdr l ) ) )
( null ? l) where l is ¸ ¸e f) )
What is the meaning of
( cons ( car ( car l ))
(frsts ( cdr l )))
( null ? l)
Now, what is the value of the line
( ( null ? l) . . . )
46
Nothing yet . We are still missing one
important ingredient in our recipe. The frst
line ( ( null ? l) . . . ) needs a value for the case
where l is the null list . We can, however,
proceed without it for now.
No, so move to the next line.
It saves ( car ( car l) ) to cons onto
(frsts ( cdr l) ) . To fnd (frsts ( cdr l) ) , we
refer to the function with the new argument
( cdr l ) .
No, so move t o the next line.
Save ( car ( car l ) ) , and recur with
(frsts ( cdr l ) ) .
No, so move t o t he next line.
Save ( car ( car l)) , and recur with
(frsts ( cdr l ) ) .
Yes.
There is no value; something is missing.
Chapter 3
What do we need to cons atoms onto?
For the purpose of consing, what value can
we give when ( null ? l) is true?
With () as a value, we now have three cons
steps to go back and pick up. We need to:
I. either
1. cons e onto ( )
2. cons c onto the value of 1
3. cons a onto the value of 2
II. or
1 . cons a onto the value of 2
2. cons c onto the value of 3
3. cons e onto ( )
Ill or
cons a onto
the cons of c onto
the cons of e onto
( )
In any case, what is the value of (frsts l)
With which of the three alternatives do you
feel most comfortable?
What is ( insertR new old lat)
where
new is toppi ng
old is fudge
and
lat is (i ce cream wi th fudge for dessert)
( insertR new old lat)
where
new is jal apeno
old is and
and
lat is (tacos tamal es and sal sa)
Cons the Magifcent
A list .
Remember The Law of Cons.
Since the fnal value must be a list , we
cannot use #t or #f. Let ' s try (quote ( ) ) .
(a c e) .
Correct ! Now you should use that one.
(ice cream with fudge toppi ng for dessert ) .
(tacos tamal es and j al apeno sal sa) .
47
( insertR new old lat)
where
new is e
old is d
and
lat is (a b L d f g d h)
I n your own words, what does
( insertR new old lat) do?
See if you can write the frst three lines of
the function insertR
Which argument changes when we recur with
insertR
How many questions can we ak about the
lat?
Which questions do we ask?
What do we know if ( null ? lat) is not true?
Which questions do we ask about the frst
element?
48
(a b L d e f g d h) .
In our words:
"It takes three arguments: the atoms new
and old, and a lat . The function insertR
builds a lat with new inserted to the right
of the frst occurrence of old. "
(defne insert
(lambda ( new old lat)
(cond . . . ) ) )
lat , because we can only look at one of its
atoms at a time.
Two.
A lat is either the null list or a nonempty
list of atoms.
First , we ak ( null ? lat) . Second, we ak
else, because else is always the last question.
We know that lat ha at leat one element .
First , we ask ( eq? ( car lat) old) . Then we
ak else, because there are no other
interesting cases.
Chapter 3
Now see if you can write the whole function
inserlR
(defne inserlR
(lambda ( new old lat)
(cond
'
(else
(cond
'
'
)
) ) ) ) ) )
What i s the value of the application
( inserl new old lat)
that we just determined
where
new is toppi ng
old is fudge
and
lat is (i ce cream wi th fudge for dessert)
So far this i s the same Ü rmber
What do we do in inserl when
( eq? ( car lat) old) is true?
How is this done?
Now we have
(defne inserlR
(lambda ( new old lat)
(cond
( ( null ? lat) (quote ( ) ) )
(else (cond
( ( eq? ( car lat) old)
( cons new ( cdr lat ) ) )
(else ( cons ( car lat)
Cons the Magifcent
( inserlR new old
( cdr lat ) ) ) ) ) ) ) ) )
Here i s our frst attempt .
(defne inserlR
(lambda ( new old lat)
(cond
( ( null ? lat) (quote ( ) ) )
(else
(cond
( ( eq? ( car lat) old) ( cdr lat) )
(else ( cons ( car lat)
( inserlR new old
( cdr lat) ) ) ) ) ) ) ) )
(i ce cream wi th for dessert ) .
When ( car lat) i s the same Ü old, we want
to insert new to the right .
Let ' s try Lonöing new onto ( cdr lat) .
Yes.
49
So what is ( insertR new old lat) now
where
new is toppi ng
old is fudge
and
lat is (i ce cream wi th fudge for dessert)
Is this the list we wanted?
What still needs to be done?
How can we include old before new
Now let ' s write the rest of the function
insertR
50
(i ce cream with toppi ng for dessert ) .
No, we have only replaced fudge with toppi ng.
Somehow we need to include the atom that is
the same as old before the atom new.
T consing old onto ( cons new ( cdr lat ) ) .
(defne insertR
(lambda ( new old lat)
(cond
( ( null ? lat) (quote ( ) ) )
(else (cond
( ( eq? ( car lat) old)
( cons old
( cons new ( cdr lat ) ) ) )
(else ( cons ( car lat)
( insertR new old
( cdr lat ) ) ) ) ) ) ) ) )
When new i s toppi ng, old i s fudge, and lat is
( i ce cream wi th fudge for dessert ) , the value of
the application, ( insertR new old lat ) , is
(i ce cream wi th fudge toppi ng for dessert) .
If you got this right , have one.
Chapter 3
Now try insertL
Hint: insertL inserts the atom new to the
left of the frst occurrence of the atom old
in lat
Did you think of a diferent way to do it?
Now try subst
Hint: ( subst new old lat) replaces the frst
occurrence of old in the lat with new
For example,
where
new is toppi ng
old is fudge
and
lat is (i ce cream with fudge for dessert)
the value is
(i ce cream with toppi ng for dessert)
Now you have the idea.
Cons the Magifcent
This much is easy, right?
(defne insertL
(lambda ( new old lat)
(cond
( ( null ? lat) (quote ( ) ) )
(else (cond
For example,
( ( eq? ( car lat) old)
( cons new
( cons old ( cdr lat ) ) ) )
(else ( cons ( car lat)
( insertL new old
( cdr lat ) ) ) ) ) ) ) ) )
( ( eq? ( car lat) old)
( cons new ( cons old ( cdr lat ) ) ) )
could have been
( ( eq? ( car lat) old)
( cons new lat) )
since ( cons old ( cdr lat) ) where old i s eq? to
( car lat) is the same as lat.
Obviously,
(defne subst
(lambda ( new old lat)
¸cond
( ( null ? lat) ¸quote ( ) ) )
¸else ¸cond
( ( eq? ( car lat) old)
( cons new ( cdr lat ) ) )
¸else ( cons ( car lat)
( subst new old
( cdr lat ) ) ) ) ) ) ) ) )
This i s the same as one of our incorrect
attempts at insertR.
51
Go cons a piece of cake onto your mouth.
Now try subst2
Hint:
( subst2 new o1 o2 lat)
replaces either the frst occurrence of o1 or
the frst occurrence of o2 by new
For example,
where
new is vani l la
o1 is chocolate
o2 is banana
and
lat is (banana ice cream
with chocolate toppi ng)
the value is
(vani l la ice cream
with chocolate topping)
Did you think of a better way?
(defne subst2
(lambda ( new o1 o2 lat)
(cond
( ( num lat) (quote ( ) ) )
(else (cond
( ( eq� ( car lat) o1 )
( cons new ( cdr lat) ) )
( ( eq� ( car lat) o2)
( cons new ( cdr lat) ) )
(else ( cons ( car lat)
( subst2 new o1 o2
( cdr lat) ) ) ) ) ) ) ) )
Replace the two eq� lines about the ( car lat)
by
( (or ( eq� ( car lat) o1 ) ( eq� ( car lat) o2) )
( cons new ( cdr lat ) ) ) .
If you got the last function, go and repeat the cakeconsing.
Do you recall what rmber does?
52
The function rmber looks at each atom of a
lat to see if it is the same a the atom a. If it
is not, rmber saves the atom and proceeds.
When it fnds the frst occurrence of a, it
stops and gives the value ( cdr lat) , or the
rest of the lat , so that the value returned is
the original lat , with only that occurrence of
a removed.
Chapter 3
Write the function multirmber which gives
as its fnal value the lat with all occurrences
of a removed.
(defne multirmber
(lambda ( a lat)
(cond
(
(else
(cond
(
(
)
) ) ) ) ) )
Hint : What do we want as the value when
( eq? ( car lat) a) is true?
Consider the example
where a is cup
and
lat is (cofee cup tea cup and hi ck cup)
Can you see how multirmber works?
( null ? lat)
else
( eq? ( car lat) a)
What is the meaning of
( cons ( car lat)
( multirmber a
( cdr lat) ) )
( null ? lat)
Cons the Magnifcent
¸defne multirmber
(lambda ( a lat)
¸cond
( ( null ? lat) ¸quote ¸ ) ) )
¸else
¸cond
( ( eq? ( car lat) a)
( multirmber a ( cdr lat ) ) )
¸else ( cons ( car lat)
( multirmber a
( cdr lat ) ) ) ) ) ) ) ) )
After the frst occurrence of a, we now
recur with ( multirmber a ( cdr lat ) ) , in
order to remove the other occurrences.
The value of the application is
(cofee tea and hi ck) .
Possibly not , so we will go through the steps
necessary to arrive at the value
(cofee tea and hi ck) .
No, so move to the next line.
Yes.
No, so move to the next line.
Save ( car lat)cofeeto be consed onto
the value of ( multirmber a ( cdr lat) ) later.
Now determine
( multirmber a ( cdr lat ) ) .
No, so move t o the next line.
53
else
( eq? ( car lat) a)
( null ? lat)
else
( eq? ( car lat) a)
What is the meaning of
( cons ( car lat)
( multirmber a
( cdr lat ) ) )
( null ? lat)
else
( eq? ( car lat) a)
( null ? lat)
( eq? ( car lat) a)
What is the meaning of
( cons ( car lat)
54
( multirmber a
( cdr lat ) ) )
Naturally.
Yes, so forget ( car lat ) , and determine
( multirmber a ( cdr lat ) ) .
No, so move to the next line.
Yes!
No, so move to the next line.
Save ( car lat)teato be consed onto the
value of ( multirmber a ( cdr lat) ) later. Now
detennine
( multirmber a ( cdr lat) ) .
No, so move t o the next line.
Okay, move on.
Yes, so forget ( car lat ) , and determine
( multirmber a ( cdr lat ) ) .
No, so move to the next line.
No, so move to the next line.
Save ( car lat)andto be consed onto the
value of ( multirmber a ( cdr lat) ) later. Now
determine
( multirmber a ( cdr lat ) ) .
Chapter 3
( null? lat)
( eq? ( car lat) a)
What is the meaning of
( cons ( car lat)
( multirmber a
( cdr lat) ) )
( null ? lat)
( eq? ( car lat) a)
( null ? lat)
Are we fnished?
What do we do next?
What do we do next?
What do we do next?
What do we do next?
Are we fnished now?
Cons the Magifcent
No, so move to the next line.
No, so move to the next line.
Save ( car lat)hi ckto be consed onto the
value of ( multirember a ( cdr lat) ) later. Now
determine
( multirmber a ( cdr lat ) ) .
No, so move t o the next line.
Yes, so forget ( car lat) , and determine
( multirmber a ( cdr lat ) ) .
Yes, so the value i s ( ) .
No, we still have several conses to pick up.
We cons the most recent ( car lat) we
havehi ckonto ( ) .
We cons and onto ¸ hi ck) .
We cons tea onto (and hi ck) .
We cons cofee onto (tea and hi ck) .
Yes.
55
Now write the function multiinsertR
(defne multiinsertR
(lambda ( new old lat)
(cond
(else
(cond
( )
( ) ) ) ) ) )
Is this function defned correctly?
¸defne multiinsertL
(lambda ( new old lat)
¸cond
( ( null ? lat) ¸quote ¸ ) ) )
¸else
¸cond
( ( eq? ( car lat) old)
( cons new
( cons old
( multiinsertL new old
lat ) ) ) )
¸else ( cons ( car lat)
( multiinsertL new old
( cdr lat ) ) ) ) ) ) ) ) )
Was the terminal condition ever reached?
56
¸defne multiinsertR
(lambda ( new old lat)
(cond
( ( null? lat) (quote ( ) ) )
(else
¸cond
( ( eq? ( car lat) old)
( cons ( car lat)
( cons new
( multiinsertR new old
( cdr lat) ) ) ) )
¸else ( cons ( car lat)
( multiinsertR new old
( cdr lat) ) ) ) ) ) ) ) )
It would also be correct to use old i n place
of ( car lat) because we know that
( eq? ( car lat) old) .
Not quite. To fnd out why, go through
( multiinsertL new old lat)
where
new is fried
old is fi sh
and
lat is (chi ps and fish or fi sh and fried) .
No, because we never get pat the frst
occurrence of old.
Chapter 3
Now, try to write the function multiinsertL
aan:
(defne multiinsertL
(lambda ( new old lat)
(cond
'
(else
(cond
( )
( ) ) ) ) ) )
(defne multiinsertL
(lambda ( new old lat)
(cond
( ( null ? lat) (quote ( ) ) )
¸else
¸cond
(( eq? ( car lat) old}
( cons new
( cons old
( multiinsertL new old
( cdr lat) ) ) ) )
¸else ( cons ( car lat)
( multiinsertL new old
( cdr lat) ) ) ) ) ) ) ) )
The Fourth Commandment
(prliminar)
Always change at least one argument while recurring. It
must be changed to be closer to termination. The changing
argument must be tested in the termination condition:
when using cdr, test termination with null?.
Now write the function multisubst
¸defne multisubst
(lambda ( new old lat)
¸cond
'
¸else
¸cond
'
'
)
) ) ) ) ) )
¸defne multisubst
{lambda ( new old lat)
¸cond
( ( null? lat) ¸quote ¸ ) ) )
¸else ¸cond
( ( eq? ( car lat) old}
( cons new
( multisubst new old
( cdr lat) ) ) )
¸else ( cons ( car lat)
( multisubst new old
( cdr lat) ) ) ) ) ) ) ) )
Cons the Magnifcent 57
 9�
Is 14 an atom?
Is ( atom? 7) true or false
where
7 is 14
Is 3 a number?
Is 3. 14159 a number?
Are 3 and 3. 14159 numbers?
What is ( add1 1 7)
where 7 is 67
1 L: 1+
S: (define add1
Cl11 bda (n}
(+ n 1 } } } }
What i s ( add1 67)
What is ( sub1 1 7)
where 7 is 5
1 L: 1
S: (define aub1
Cl11 bda (n}
( n 1 } } } }
Numbers Games
Yes, because all numbers are atoms.
Tue, because 14 is an atom.
Yes,
but we do not consider negative numbers.
Yes,
but we consider only whole numbers.
Yes,
but the only numbers we use are the
nonnegative integers ¸i. e. , 0, 1, 2, 3, 4, . . . ) .
68.
Also 68,
because we don' t need to say "where 7 is
67" when the argument is a number.
4.
59
What is ( sub1 0}
Is ( zer?
1
0} true or false?
¯ L: ZeI0§
Is ( zer? 1492} true or false?
What is ( + 46 12}
Ty to write the function +
Hint : It uses zer? add1 1 and sub1 1
¯ Remember to use our defnitions for addI and aubI.
But didn' t we just violate The First
Commandment?
If zer P is like null?
is add1 like cons
60
No answer. 1
1 ( subl R) , where R i s Û, ha no answer because we consider
only nonnegative numbers. In pratice, this result is 1.
Tue.
Flse.
58.
(defne + 1
(lambda ( n M)
(cond
( ( zero? M) n)
(else ( add1 ( + n ( sub1 M) ) ) ) ) ) )
Wasn' t that easy?
1 L, S: This is like +. Write it a o+ (see prefae) .
Yes, but we can treat zer? like null ? since
zer? asks if a number is empty and null?
asks if a list is empty.
Yes! cons builds lists and add1 builds
numbers.
Chapter 4
What is (  14 3)
What is (  17 9)
What is (  18 25)
Ty to write the function 
Hint: Use sub1
Ca you describe how (  7 Û) works?
Is this a tup?
(2 11 3 79 47 6)
Is this a tup?
(8 55 5 555)
Is this a tup?
(1 2 8 appl e 4 3)
Is this a tup?
(3 (7 4) 13 9)
Numbers Games
1 1 .
8.
No answer. There are no negative numbers.
How about this:
(defne  1
(lambda ¸7 Û)
(cond
( ( zer? Û) 7)
(else (sub1 (  7 (sub1 Û) ) ) ) ) ) )
1 L, S: This i s like . Write i t a o  (see prefae) .
It takes two numbers Ü arguments, and
reduces the second until it hits zero. It
subtracts one from the result Ü many times
Ü it did to cause the second one to reach
zero.
Yes: tup is short for tuple.
Yes, of course, it is also a list of numbers.
No, it is just a list of atoms.
No, because it is not a list of numbers.
(7 4) is not a number.
61
Is this a tup?
()
What is ( addtup tup)
where
tup is (3 5 2 8)
What is ( addtup tup)
where
tup is ( 15 6 7 12 3)
What does addtup do?
What is the natural way to build numbers
from a list?
When building lists with cons
the value of the terminal condition is ( )
What should be the value of the terminal
condition when building numbers with ÷
What is the natural terminal condition for a
list?
What is the natural terminal condition for a
tup?
When we build a number from a list of
numbers, what should the terminal condition
line look like?
What is the terminal condition line of
addtup
62
Yes, it is a list of zero numbers. This special
case is the empty tup.
18.
43.
It builds a number by totaling all the
numbers in its argument.
Use ÷ in place of cons : ÷ builds numbers in
the same way as cons builds lists.
0.
( null ? l ) .
( null ? tup) .
( ( null ? tup) 0) , j ust as ( ( null ? l) (quote ( ) ) )
i s often the terminal condition line for lists.
( ( null? tup) 0) .
Chapter 4
How is a lat defned?
How is a tup defned?
What is used in the natural recursion on a
list?
What is used in the natural recursion on a
tup?
Why?
How many questions do we need to ak
about a list?
How many questions do we need to ak
about a tup?
How is a number defned?
What is the natural terminal condition for
numbers?
What is the natural recursion on a number?
How many questions do we need to ak
about a number?
Numbers Games
It is either an empty list , or it contains an
atom, ( car lat) , and a rest, ( cdr lat) , that is
also a lat .
It is either an empty list , or it contains a
number and a rest that is also a tup.
( cdr lat ) .
( cdr tup) .
Because the rest of a nonempty list i s a list
and the rest of a nonempty tup is a tup.
Two.
Two, because it is either empty or it is a
number and a rest, which is again a tup.
It is either zero or it is one added to a rest,
where rest is again a number.
( zero ? 7) .
( sub1 7) ·
Two.
63
The First Commandment
(frst revision)
When recurring on a list of atoms, lat , ask two questions
about it: ( null ? lat ) and else.
When recurring on a number, n, ask two questions about
it: ( zero ? n) and else.
What does cons do?
What does addtup do?
What is the terminal condition line of
addtup
What is the natural recursion for addtup
What does addtup use to build a number?
Fill in the dots in the following defnition:
(defne addtup
(lambda ( tup)
(cond
( ( null ? tup) 0)
(else . . . ) ) ) )
What i s ¸ x 5 3)
What is ¸ x 13 4)
64
It builds lists.
It builds a number by totaling all the
numbers in a tup.
( ( null? tup) 0) .
( addtup ( cdr tup) ) .
It uses +, because + builds numbers, too!
Here is what we flled in:
( + ( car tup) ( addtup ( cdr tup) ) ) .
Notice the similarity between this line, and
the lat line of the function rmber:
( cons ( car lat ) ( rmber a ( cdr lat ) ) ) .
15.
52.
Chapter 4
What does ¸ ? Ñ M) do?
What is the terminal condition line for ?
Since (zerP M) is the terminal condition, M
must eventually be reduced to zero. What
function is used to do this?
It builds up a number by adding Ñ up M
times.
( ( zerP M) 0) , because W ? 0 ~ 0.
sub1 .
The Fourth Commandment
(frst rvision)
Always change at least one argument while recurring. It
must be changed to be closer to termination. The changing
argument must be tested in the termination condition:
when using cdr, test termination with null ? and
when using sub1 , test termination with zero ?.
What is another name for ¸ ? Ñ ( sub1 M) ) in
this case?
Ty to write the function ?
Number Games
It' s the natural recursion for ? .
(defne ?
Î
(lambda ( Ñ M)
(cond
( ( zerP M) 0)
(else ( + Ñ ¦ ? Ñ ( sub1 M) ) ) ) ) ) )
1 L, S: This i s lik •.
65
What is ¸ x 12 3)
( zero ? Û)
What is the meaning of
( + n ¸ x n (sub1 Û) ) )
What are the new arguments of
¸ x n Û)
( zero ? Û)
What is the meaning of
¸ ÷n ¸ x n ( sub1 Û) ) )
What are the new arguments of
¸ x n Û)
( zer? Û)
What is the meaning of
¸ ÷n ¸ x n ( sub1 Û) ) )
What i s the value of the line
( ( zer? M) 0)
Are we fnished yet?
66
36,
but let ' s follow through the function one
time to see how we get this value.
No.
It adds n ¸where n ° 12) to the natural
recursion. If x is correct then
¸ x 12 ( sub1 3))
should be 24.
n is 12, and Û is 2.
No.
It adds n ¸where n ° 12) to ¸ x n ( sub1 Û) ) .
n is 12, and Û is 1 .
No.
It adds n ¸where n ° 12) to ¸ x n ( sub1 Û) ) ·
0, because ( zer? Û) is now true.
No.
Chapter 4
Why not?
What is the value of the original application?
Because we still have three +es to pick up.
Add 12 to 12 to 12 to 0 yielding 36,
Notice that Ñ has been +ed M times.
( x 12 3) = 12 + ( x 12 2)
= 12 + 12 + ( x 12 1)
Argue, using equations, that x is the
conventional multiplication of nonnegative
integers, where n is 12 and Ï is 3.
= 12 + 12 + 12 + ( ? 12 0)
= 12 + 12 + 12 + 0,
Again, why is 0 the value for the terminal
condition line in x
which is as we expected. This technique
works for all recursive functions, not j ust
those that use numbers. You can use this
approach to write functions as well as to
argue their correctness.
Because 0 will not afect +. That is,
n + O = n.
The Fifh Commandment
When building a value with + , always use 0 for the vlue of the
terminating line, for adding 0 does not change the value of an
addition.
When building a vlue with x , always use 1 for the vlue of the
terminating line, for multiplying by 1 does not change the vlue
of a multiplication.
When building a vlue with cons, always consider ( ) for the vlue
of the terminating line.
What is ( tup+ tup1 tup2)
where
tup1 is (3 6 9 1 1 4)
and
tup2 is (8 5 2 0 7)
Numbers Games
( 1 1 1 1 11 11 1 1) .
67
What is ( tup+ tup1 tup2)
where
tup1 is (2 3)
and
tup2 is (4 6)
What does ( tup+ tup1 tup2) do?
What is unusual about tup+
If you recur on one tup how many questions
do you have to ask?
When recurring on two tups, how many
questions need to be asked about the tups?
Do you mean the questions
(and ( null ' tup1 ) ( nul tup2) )
( nul tup1 )
( nul tup2)
and
else
Can the frst tup be () at the same time as
the second is other than ( )
Does this mean
(and ( nul tup1 ) ( null ' tup2) )
and
else
are the only questions we need to ask?
68
¸69).
It ads the frst number of tup1 to the frst
number of tup2, then it ads the second
number of tup1 to the second number of
tup2, and so on, building a tup of the
answers, for tups of the same length.
It looks at each element of two tups at the
same time, or in other words, it recurs on
two tups.
Two, they are ( null ? tup) and else.
Four: if the frst tup is empty or nonempty,
and if the second tup is empty or nonempty.
Yes.
No, because the tups must have the same
length.
Yes,
because ( null ' tup1 ) is true exactly when
( nul tup2) is true.
Cbapter 4
Write the function tup+
What are the arguments of + in the last line?
What are the arguments of cons in the last
line?
What is ( tup+ tup1 tup2)
where
tup1 is (3 /)
and
tup2 is ¸46)
( null ? tup1 )
( cons
( + ( car tup1 ) ( car tup2) )
( tup+ ( cdr tup1 ) ( cdr tup2) ) )
Why does the natural recursion include the
cdr of both arguments?
( null ? tup1 )
where
tup1 is now (7)
and
tup2 is now (6)
Numbers Games
(defne tup+
(lambda ( tup1 tup2)
(cond
( ( and ( null? tup1 ) ( null ? tup2) )
(quote ( ) ) )
(else
( cons ¸+ ( car tup1 ) ( car tup2) )
( tup+
( cdr tup1 ) ( cdr tup2) ) ) ) ) ) )
( car tup1 ) and ( car tup2) .
( + ( car tup1 ) ( car tup2) ) and
( tup+ ( cdr tup1 ) ( cdr tup2) ) .
(7 13).
But let ' s see how it works.
No.
cons 7 onto the natural recursion:
( tup+ ( cdr tup1 ) ( cdr tup2) ) .
Because the typical element of the fnal value
uses the car of both tups, so now we are
ready to consider the rest of both tups.
No.
69
( cons
( + ( car tup1 ) ( car tup2) )
( tup+ ( cdr tup1 ) ( cdr tup2) ) )
( null ? tup1 )
Then, what must be the value?
What is the value of the application?
What problem arises when we want
( tup+ tup1 tup2)
where
tup1 is (3 7)
and
tup2 is ( 4 6 8 1)
Can we still write tup+ even i f the tups are
not the same length?
What new terminal condition line can we
add to get the correct fnal value?
What is ( tup+ tup1 tup2)
where
tup1 is (3 7 8 1)
and
tup2 is (4 6)
What do we need to include in our function?
What does the second new line look like?
70
cons 13 onto the natural recursion.
Yes.
( ) , because ( null ? tup2) must be true.
(7 13) . That is, the cons of 7 onto the cons
of 13 onto ¸ ) .
No answer, since tup1 will become null
before tup2.
See The First Commandment: We did not
ask all the necessary questions!
But, we would like the fnal value to be
(7 13 8 1) .
Yes!
Add
( ( null ? tup1 ) tup2) .
No answer, since tup2 will become null
before tup1.
See The First Commandment: We did not
ask all the necessary questions!
We need to ask two more questions:
( null ? tup1 ) and ( null ? tup2) .
( ( null ? tup2) tup1 ) .
Chapter 4
Here is a defnition of tup+ that works for
any two tups:
(defne tup+
(lambda ( tup1 tup2)
(cond
((and ( null ? tup1 ) ( null ? tup2) )
(quote ( ) ) )
( ( null ? tup1 ) tup2)
( ( null ? tup2) tup1 )
(else
( cons ¸+ ( car tup1 ) ( car tup2) )
( tup+
( cdr tup 1 ) ( cdr tup2) ) ) ) ) ) )
Can you simplify it?
(defne tup+
(lambda ( tup1 tup2)
(cond
( ( null ? tup1 ) tup2)
( ( null ? tup2) tup1 )
¸else
( cons ( + ( car tup1 ) ( car tup2) )
( tup+
( cdr tup1 ) ( cdr tup2) ) ) ) ) ) )
Does the order of the two terminal conditions No.
matter?
Is else the last question?
What is (> 12 133)
What is ( > 120 11)
On how many numbers do we have t o recur?
How do we recur?
When do we recur?
How many questions do we have to ask
about n and Û
Numbers Games
Yes, because either ( null ? tup1 ) or
( null ? tup2) is true if either one of them does
not contain at least one number.
#ffalse.
#t true.
Two, n and Û
With (sub1 n) and ( sub1 Û) 
When we know neither number is equal to 0.
Three: ( zero ? n), ( zer? M) ¿ and else.
71
Can you write the function > now using
zer? and sub1
Is the way we wrote ¸ > 7 Û) correct?
( zer? 3)
(zer? 3)
What is the meaning of
¸ > (sub1 7) (sub1 Û) )
( zer? 2)
( zer? 2)
What is the meaning of
¸ > ( sub1 7) (sub1 Û) )
(zero ? 1)
(zer? 1)
What i s the meaning of
¸ > ( sub1 7) (sub1 Û) )
72
How about
(defne >
(lambda ( 7 Û)
(CLnd
( ( zer? Û) #t )
( ( zer? 7) #f )
(else ¸ > ( sub1 7) ( sub1 Û) ) ) ) ) )
No, try i t for the case where 7 and Û are the
same number. Let 7 and Û be 3.
No, so move to the next question.
No, so move to the next question.
Recur, but with both arguments reduced by
one.
No, so move to the next question.
No, so move to the next question.
Recur, but with both arguments closer to
zero by one.
No, so move to the next question.
No, so move to the next question.
Recur, but with both arguments reduced by
one.
Chapter 4
(zer? 0) Yes, so the value of ¸ > 7 Û) is #t .
Is this correct? No, because 3 is not greater than 3.
Does the order of the two terminal conditions Think about it.
matter?
Does the order of the two terminal conditions Ty it out !
matter?
Does the order of the two previous answers
matter?
How can we change the function > to take
care of this subtle problem?
What is ( < 4 6)
( < 8 3)
(< 6 6)
Now try to write <
Number Games
Yes. Think frst , then try.
Switch the zero ? lines:
(defne >
(lambda ( 7 Û)
#t .
#f.
#f.
(cond
( ( zero ? 7) #f )
( ( zero ? Û) #t )
(else ¸ > (sub1 7) ( sub1 Û) ) ) ) ) )
(defne <
(lambda ( 7 Û)
(cond
( ( zero ? Û) #f )
( ( zer? 7) #t )
(else ( < (sub1 7) ( sub1 Û) ) ) ) ) )
73
Here is the defnition of =
(defne =
(lambda ¸ H Û)
(cond
( ( zer? Û) ( zero ? H) )
( ( zero ? H) #f )
(else (= ( sub1 H) ( sub1 Û) ) ) ) ) )
Rewrite = using < and >
Does this mean we have two diferent
functions for testing equality of atoms?
¸¡ 1 1 )
¸¡2 3)
¸¡ 5 3)
Now write the function ¡
Hint : See the The First and Fifth
Commandments.
What is a good name for this function?
(defne ???
(lambda ( H Û)
(cond
( ( < H Û) 0)
(else ( add1 ( ??? ( ¯ H Û) Û) ) ) ) ) )
74
(defne =
(lambda ( H Û)
(cond
( ( > H Û) #f )
( ( < H Û) #f )
(else #t ) ) ) )
Yes, they are ° for atoms that are numbers
and eq? for the others.
1 .
8.
125.
(defne ¡'
(lambda ( H Û)
(cond
( ( zero ? Û) 1)
(else ¸ 7 H ¸ ¡H ( sub1 Û) ) ) ) ) ) )
' L, S: This i s like expt.
We have never seen this kind of defnition
before; the natural recursion also looks
strange.
Chapter 4
What does the frst question check?
And what happens in the second line?
So what does the function do?
And what do we call this?
What is ( + 15 4)
How do we get there?
It determines whether the frst argument is
less than the second one.
We recur with a frst argument from which
we subtract the second argument . When the
function returns, we add 1 to the result .
It counts how many times the second
argument fts into the frst one.
Division.
(defne +1
(lambda (n m)
(cond
( ( < n m) O)
(else ( add1 ( + (
n m) m) ) ) ) ) )
¯ L: (defu quotient ( n m}
(values (trucate (/ n m} } } }
S : This is like quotient.
Eay, it is 3.
Eay, too:
( ÷ 15 4) ¯ 1 + ( + 11 4)
1 + ( 1 + ( + 7 4))
1 + ( 1 + ( 1 + ( + 3 4) ) )
¯ 1 + ( 1 + ( 1 + 0) ) .
Wouldn' t a (ham and cheese on rye) be good right now?
Don' t forget the mustard!
Numbers Games 75
What is the value of ( length lat)
where
lat is ¸ hotdogs with mustard sauerkraut
and pi ckl es)
What is ( length lat)
where
lat is ¸ ham and cheese on rye)
Now try to write the function length
What is (pick n lat)
where n is 4
and
lat is ¸ l asagna spaghetti ravi ol i
macaroni meatbal l )
What is (pick 0 lat)
where lat is ¸a)
Ty to write the function pick
What is ¸ ÍÛ pick n lat)
where n is 3
and
lat is ¸ hotdogs wi th hot mustard)
76
6.
5.
(defne length
(lambda ( lat)
(cond
( ( null ? lat) 0)
(else ( add1 ( length ( cdr lat) ) ) ) ) ) )
macaroni .
No answer.
(defne pick
(lambda ( n lat)
(cond
( ( zer? ( sub1 n) ) ( car lat) )
(else (pick ( sub1 n) ( cdr lat) ) ) ) ) )
¸ hotdogs wi th mustard) .
Chapter 4
Now try to write rmpick
Is ( number?1 a) true or false
where a is tomato
1 L: nuberp
Is ( number? 76) true or false?
Can you write number? which is true if its
argument is a numeric atom and false if it is
anthing else?
Now using number? write the function
nonums which gives Ü a fnal value a lat
obtained by removing all the numbers from
the lat . For example,
where
lat is (5 pears 6 prunes 9 dates)
the value of ( nonums lat) is
(pears prunes dates)
Numbers Games
(defne rm pick
(lambda ( n lat)
(cond
False.
Tue.
( ( zero ? ( sub1 n) ) ( cdr lat) )
(else ( cons ( car lat)
( rmpick (sub1 n)
( cdr lat ) ) ) ) ) ) )
No: number?, like add1 , sub1 , zero ?, car,
cdr, cons , null ?, eq?, and atom?, is a
primitive function.
(defne nonums
(lambda ( lat)
(cond
( ( null ? lat) (quote ( ) ) )
(else (cond
( ( number? ( car lat) )
( nonums ( cdr lat ) ) )
(else ( cons ( car lat)
( nonums
( cdr lat ) ) ) ) ) ) ) ) )
77
Now write allnums which extracts a tup
from a lat using all the numbers in the lat .
Write the function eqan? which is true if its
two arguments ( a1 and a2) are the same
atom. Remember to use ¯ for numbers and
eq? for all other atoms.
Can we assume that all functions written
using eq? can be generalized by replacing eq?
by eqan?
Now write the function occur which counts
the number of times an atom a appears in a
lat
(defne occur
(lambda (a lat)
(cond
78
'
(else
(cond
'
'
)
) ) ) ) ) )
(defne allnums
(lambda ( lat)
(cond
( ( null ? lat) (quote ( ) ) )
(else
(cond
( ( number? ( car lat) )
( cons ( car lat)
( allnums ( cdr lat) ) ) )
(else ( allnums ( cdr lat) ) ) ) ) ) ) )
(defne eqan?
(lambda ( a1 a2)
(cond
((and ( number? a1 ) ( number? a2) )
¸ ¯ a1 a2) )
( (or ( number? a1 ) ( number? a2) )
#f )
(else ( eq? a1 a2) ) ) ) )
Yes, except , of course, for eqan? itself.
(defne occur
(lambda ( a lat)
(cond
( ( null ? lat) 0)
(else
(cond
( ( eq? ( car lat) a)
( add1 ( occur a ( cdr lat) ) ) )
(else ( occur a ( cdr lat ) ) ) ) ) ) ) )
Chapter 4
Write the function one ? where ( one ? n) is #t
if n is 1 and #f ¸i. e. , false) otherwise.
Guess how we can further simplify this
function, making it a oneliner.
Now rewrite the function rmpick that
removes the Î`¯ atom from a lat. For
example,
where
n is 3
and
lat is ( l emon meri ngue sal ty pi e)
the value of ( rm pick n lat) is
(l emon meri ngue pi e)
Use the function one ? in your answer.
Numbers Games
(defne one ?
(lambda ( n)
(cond
( ( zer? n) #f )
(else ( zer? ( sub1 n) ) ) ) ) )
or
(defne one ?
(lambda ( n)
(cond
(else ( = n 1) ) ) ) )
By removing the ( cond . . . ) clause:
(defne one ?
(lambda ( n)
( = n 1) ) )
(defne rmpick
(lambda ( n lat)
(cond
( ( one ? n) ( cdr lat) )
(else ( cons ( car lat)
( rmpick ( sub1 n)
( cdr lat ) ) ) ) ) ) )
79
�'
�·
What is ( rmber* a l}
where a is cup
and
l is ((cofee) cup ((tea) cup)
(and (hick} } cup)
"rmber*" is pronounced "remberstar. "
What is ( rmber* a l}
where a is sauce
and
l is (((tomato sauce))
((bean) sauce)
(and ((flyi ng)) sauce))
Now write rmber*
t
Here is the skeleton:
(defne rmber*
(lambda ( a l}
(cond
'
'
(
¹
¹
) ) ) )
t
" . . . ¯ ma 08 think "oh D gawd."
( lat ? l}
where
l is (( (tomato sauce))
((bean) sauce)
(and ( (flyi ng) ) sauce))
*
Oh My Gawd
*
: It 's Fl of Stas
((cofee) ((tea) ) (and (hick) ) } .
(( (tomato) )
((bean) )
( and ( (flying) ) ) ) .
(defne rmber*
(lambda ( a l}
(cond
( ( nUll ? l} (quote ( ) ) )
( ( atom? ( car l}}
(cond
( ( eq? ( car l} a)
( rmber* a ( cdr l )))
¸else ( cons ( car l)
( rmber* a ( cdr l ) ) } ) ) )
¸else ( cons ( rmber* a ( car l } }
( rmber* a ( cdr l ) ) } ) ) ) )
Using arguments from one of our previous
examples, follow through this to see how it
works. Notice that now we are recurring
down the car of the list , instead of just the
cdr of the list .
#f.
81
Is ( cÛr l) an atom
where
l is ( ( (tomato sauce) )
( ( bean) sauce)
(and ( (flyi ng) ) sauce) )
What is ( insertR * new old l)
where
new is roast
old is chuck
and
l is ( ( ho much (wood) )
coul d
( ( a (wood) chuck) )
( ( (chuck) ) )
( i f ( a) ((wood chuck) ) )
coul d chuck wood)
Now write the function insertR * which
inserts the atom new to the right of old
regardless of where old occurs.
(defÎe insertR *
(lÜbda ( new old l)
(LoÎd
( )
( )
( ) ) ) )
How are insertR * and rmber* similar?
82
No.
( ( how much (wood) )
coul d
((a (wood) chuck roast) )
( ( (chuck roast) ) )
( i f (a) ((wood chuck roast) ) )
coul d chuck roast wood) .
(defÎe insertR *
(lambda ( new old l)
(LoÎd
( ( null ? l) (quote ( ) ) )
( ( atom? ( car l ) )
(LoÎd
(( eq? ( car l) old)
( cons old
¸ cons new
( insertR * new old
( cdr l ) ) ) ) )
(else ¸ cons ¸ car l )
( insertR * new old
( cdr l ) ) ) ) ) )
(else ( cons ( insertR * new old
( car l ))
( insertR * new old
¸ cdr l ) ) ) ) ) ) )
Each function asks three questions.
Chapter 5
The First Commandment
(fnal version)
When recurring on a list of atoms, lat , ask two questions
about it: ( null ? lat ) and else.
When recurring on a number, n, ask two questions about
it: (zero ? n) and else.
When recurring on a list of Sexpressions, l , ask three
question about it: ( null ? l ) , ( atom? ( car l ) ) , and else.
How are insertR * and rmber* similar? Each function recurs on the car of its
argument when it fnds out that the
argument ' s car is a list .
How are rmber* and multirmber diferent?
How are insertR * and rmber* similar?
How are all *functions similar?
Why?
*
Ob My Gawd
*
: It 's Fl of Stars
The function multirmber does not recur
with the car. The function rmber* recurs
with the car as well as with the cdr. It
recurs with the car when it fnds out that
the car is a list .
They both recur with the car, whenever the
car is a list , as well as with the cdr.
They all ask three questions and recur with
the car as well as with the cdr, whenever the
car is a list.
Because all *functions work on lists that are
either
 empty,
 an atom consed onto a list , or
 a list consed onto a list .
83
The Fourth Commandment
(fnal version)
Always change at least one argument while recurring.
When recurring on a list of atoms, lat , use ( cdr lat ) . When
recurring on a number, n, use ( sub1 n) . And when recur
ring on a list of Sexpressions, l , use ( car l) and ( cdr l) if
neither ( null ? l ) nor ( atom? ( car l ) ) are true.
It must be changed to be closer to termination. The chang
ing argument must be tested in the termination condition:
when using cdr, test termination with null ? and
when using sub1 , test termination with zero ?.
( occursomething Ú l)
where
5.
Ú i s banana
and
l is ( ( banana)
(spl i t ( ( ( ( banana i ce) ) )
(cream ( banana) )
sherbet) )
( banana)
( bread)
(banana brandy) )
What is a better name for
occursomething
84
occur*.
Chapter 5
Write occur*
(dÜfne occur*
(lambda (a l)
(cond
<
< 
( 
( subst * new old l)
where
new is orange
old is banana
ad
l is ( ( banana)
)
)
) ) ) )
(spl i t ( ( ( ( banana i ce) ) )
(cream (banana) )
sherbet) )
(banana)
(bread)
(banana brandy) )
Write subst *
(defne subst *
(lambda ( new old l)
¸cond
< 
<
<
)
)
) ) ) )
*Oh My Gawd*: It 's Fll of Stars
(defne occur*
(lambda (a l)
(cond
( ( null ? l) 0)
( ( atom? ( car l ) )
(cond
( ( eq? ( car l) a)
( add1 ( occur* a ( cdr l ) ) ) )
(else ( occur* a ( cdr l ) ) ) ) )
(else ( + ( occur* a ( car l ) )
( occur* a ( cdr l ) ) ) ) ) ) )
((orange)
(spl i t ( ( ( (orange i ce) ) )
(cream (orange) )
sherbet) )
(orange)
( bread)
(orange brandy) ) .
¸defne subst*
(lambda ( new old l)
¸cond
( ( null ? l) (quote ( ) ) )
( ( atom? ( car l ) )
¸cond
(( eq? ( car l) old)
( cons new
( subst * new old ( cdr l ) ) ) )
¸else ( cons ( car l)
(subst * new old
( cdr l ) ) ) ) ) )
¸else
( cons ( subst* new old ( car l ) )
( subst* new old ( cdr l ) ) ) ) ) ) )
85
What is ( insertL * new old l)
where
new is peeker
old is chuck
and
l is ( ( how much (wood) )
coul d
( (a (wood) chuck))
( ( (chuck) ) )
( i f ( a) ( (wood chuck) ) )
coul d chuck wood)
Write insertL *
(defne insertL *
(lambda ¸ new old l )
(Lond
(
¯
(
(
¸ member* Ú l)
where Ú is chi ps
and
)
)
) ) ) )
l is ( ( potato) (chi ps ( (wi th) fi sh) (chi ps) ) )
86
( ( how much (wood) )
coul d
((a (wood) peeker chuck))
( ( ( peeker chuck) ) )
( i f (a) ((wood peeker chuck) ) )
coul d peeker chuck wood) .
(defne insertL *
(lambda ¸ new old l)
(Lond
( ¸ null? l) (quote ¸ ) ) )
¸ ¸ atom? ¸ car l) )
(Lond
( ( eq? ¸ car l) old)
¸ cons new
¸ cons old
( insertL * new old
¸ cdr l) ) ) ) )
(else ¸ cons ¸ car l)
( insertL * new old
¸ cdr l) ) ) ) ) )
(else ¸ cons ( insertL * new old
¸ car l) )
( insertL * new old
¸ cdr l) ) ) ) ) ) )
#t g because the atom chi ps appears i n the
list l.
Chapter 5
Write member*
(defne member*
(lambda ¸ Û l)
(cond
(
(
(
¯
)
)
) ) ) )
What i s ( member* a l)
where
Û is chi ps
and
l is ( (potato) (chi ps ( (wi th) fi sh) (chi ps) ) )
Which chi ps did i t fnd?
What is ( lefmost l)
where
l is ( ( potato) (chi ps ( (wi th) fi sh) (chi ps) ) )
What i s ( lefmost l)
where
l is ( ( ( hot) (tuna (and) ) ) cheese)
What is ( lefmost l)
where
l is ( ( ( ( ) four)) 17 (seventeen) )
What i s ( lefmost (quote ( ) ) )
Ca you describe what lefmost does?
*
Oh My Gawd
*
: It 's Fn of Stars
(defne member*
(lambda (a l)
(cond
#t .
( ( null ? l) #f )
( ( atom? ( car l) )
(or ( eq? ( car l) a)
( member* a ( cdr l) ) ) )
(else (or ( member* a ( car l ) )
( member* a ( cdr l ) ) ) ) ) ) )
( ( potato) (chi ps ( (wi th) fi sh) (chi ps) ) ) .
potato.
hot.
No answer.
No answer.
Here is our description:
"The function lefmost fnds the leftmost
atom in a nonempty list of Sexpressions
that does not contain the empty list. "
87
Is lefmost a *function?
Does lefmost need to ask questions about all
three possible cases?
Now see if you can write the function
lefmost
(defne lefmost
(lambda ( l )
(LLnd
<
<
)
) ) ) )
Do you remember what ¸LÏ . ) does?
What is
(and ( atom? ( car l ) )
( eq? ( car l) x) )
where
x is pi zza
and
l is (mozzarel l a pi zza)
Why is it false?
88
It works on lists of Sexpressions, but it only
recurs on the car.
No, it only needs to ask two questions. We
agreed that lefmost works on nonempty
lists that don' t contain empty lists.
(defne lefmost
(lambda ( l )
(LLnd
( ( atom? ( car l ) ) ( car l ))
(else ( lefmost ( car l ) ) ) ) ) )
¸LÏ . . ) asks questions one at a time until it
fnds one that is true. Then ¸LÏ . ) stops,
making its value true. If it cannot fnd a true
argument , the value of ¸LÏ · · ) is false.
#f.
Since (and . . . ) asks ( atom? ( car l ) ) , which
is true, it then asks ( eq? ( car l) x ) , which is
false; hence it is #f.
Chapter 5
What is
(and ( atom? ( car l ) )
( eq? ( car l) x) )
where
x is pi zza
and
l is ¸ ¸mozzarel l a mushroom) pi zza)
Why is it false?
Give an example for x and l where
(and ( atom? ( car l ) )
( eq? ( car l) x) )
i s true.
Put in your own words what (and . . . ) does.
Tue or false: it is possible that one of the
arguments of (and . . . ) and ¸LÏ . . . ) is not
considered? '
' ( cond . . . ) also ha the property of not considering all of
its arguments. Because of this property, however, neither
(and . . . ) nor (or . . . ) can be def ned a functions in terms
of (cond . . . ) , though both (and . . . ) and (or . . . ) can be
expressed a abbreviations of ( cond . . . ,expressions:
(and t {) ~ (cond (t {) (else #f))
and
(or t {) ~ (cond , t #t) (else {))
( eqlist ? l1 l2)
where
l1 is ¸strawberry ice cream)
and
l2 is ¸strawberry ice cream)
*Oh My Gawd*: It 's Fll of Stars
#f.
Since (and . . . ) asks ( atom? ( car l ) ) , and
( car l) is not an atom; so it is #f.
Here' s one:
x is pi zza
and
l is ¸ pi zza ¸tastes good) ) .
We put it in our words:
"(and . . . ) asks questions one at a time
until it fnds one whose value is false. Then
(and . . . ) stops with false. If none of the
expressions are false, (and . . . ) is true. "
Tue, because (and . . . ) stops if the frst
argument has the value #f, and ¸LÏ )
stops if the frst argument has the value #t .
#t .
89
( eqlist ? l1 l2)
where
l1 is (strawberry i ce cream)
and
l2 is (strawberry cream i ce)
( eqlist ? l1 l2)
where
l1 is (banana ( (spl i t) ) )
and
l2 is ( ( banana) (spl i t) )
( eqlist ? l 1 l2)
where
l1 is (beef ( (sausage) ) (and (soda) ) )
and
l2 is (beef ( (sal ami ) ) (and (soda) ) )
( eqlist ? l 1 l2)
where
l1 is (beef ( (sausage) ) (and (soda) ) )
and
l2 is ( beef ( (sausage) ) (and (soda) ) )
What i s eqlist ?
How many questions will eqlist ? have to ak
about its arguments?
Can you explain why there are nine
questions?
90
#f.
#f.
#f, but almost #t .
#t . That ' s better.
It is a function that determines if two lists
are equal.
Nine.
Here are our words:
"Each argument may be either
 empty,
 an atom consed onto a list , or
 a list consed onto a list .
For example, at the same time a the frst
argument may be the empty list , the
second argument could be the empty list or
have an atom or a list in the LÚÍ position. "
Chapter 5
Write eqlist ? using eqan?
Is it oky to ask ( atom? ( car l2) ) in the
second question?
And why is the third question ( null ? l1 )
Tue or false: if the frst argument is ( )
eqlist ? responds with #t i n only one case.
*Oh My Gawd
*
: It 's Fl of Stars
(defne eqlist ?
(lambda ( l1 l2)
(Lond
( ( and ( null ? l1 ) ( null ? l2) ) #t )
( ( and ( null ? l1 ) ( atom? ( car l2) ) )
#f )
( ( null? l1 ) #f )
( ( and ( atom? ( car l1 ) ) ( null ? l2) )
#f )
( ( and ( atom? ( car l1 ) )
( atom? ( car l2) ) )
(and ( eqan? ( car l1 ) ( car l2) )
( eqlist ? ( cdr l 1 ) ( cdr l2) ) ) )
( ( atom? ( car l1 ) ) #f )
( ( null? l2) #f )
( ( atom? ( car l2) ) #f )
(elÜe
(and ( eqlist ? ( car l1 ) ( car l2) )
( eqlist ? ( cdr l 1 ) ( cdr l2) ) ) ) ) ) )
Yes, because we know that the second list
cannot be empty. Otherwise the frst
question would have been true.
At that point , we know that when the frst
argument is empty, the second argument is
neither the empty list nor a list with Ü atom
as the frst element . If ( null ? l1 ) is true now,
the second argument must be a list whose
frst element is also a list.
Tue.
For ( eqlist ? (quote ( ) ) l2) to be true, l2
must also be the empty list.
91
Does this mean that the questions
(and ( null ? 11 ) ( null ? l2) )
and
¸LÏ ( null ? 11 ) ( null ? 12) )
sufce to determine the answer i n the frst
three cases?
Rewrite eqlist ?
What i s an Sexpression?
How many questions does equal? ask to
determine whether two Sexpressions are the
same?
Write equal ?
92
Yes. If the frst question is true, eqlist ?
responds with #t ; otherwise, the answer is
#f.
(defne eqlist ?
(lambda ( l1 12)
(LLnd
((and ( null? 11 ) ( null? 12) ) #t )
¸ ¸LÏ ( null ? 11 ) ( null ? 12) ) #f )
((and ( atom? ( car l1 ) )
( atom? ( car 12) ) )
(and ( eqan? ( car 11 ) ( car 12) )
( eqlist ? ( cdr 11 ) ( cdr 12) ) ) )
¸ ¸L1 ( atom? ( car l1 ) )
( atom? ( car 12) ) )
#f )
(else
(and ( eqlist ? ( car 11 ) ( car 12) )
( eqlist? ( cdr 11 ) ( cdr l2) ) )))))
An Sexpression i s either an atom or a
(possibly empty) list of Sexpressions.
Four. The frst argument may be an atom or
a list of Sexpressions at the same time a
the second argument may be an atom or a
list of Sexpresssions.
(defne equal ?
(lambda (s1 s2)
(LLnd
((and ( atom? s1 ) ( atom? s2))
( eqan? s1 s2) )
( ( atom? s1 ) #f )
( ( atom? s2) #f )
(else ( eqlist? s1 s2) ) ) ) )
Chapter 5
Why is the second question ( atom? s1 )
And why is the third question ( atom? s2)
Ca we summarize the second question and
the third question as
¸L1 ( atom? s1 ) ( atom? s2) )
Simplify equal ?
Does equal ? ask enough questions?
Now, rewrite eqlist ? using equal?
*Ob My Gawd*: It 's Fll of Stars
If it is true, we know that the frst argument
is an atom and the second argument is a list .
By the time we ask the third question we
know that the frst argument is not an atom.
So all we need to know in order to
distinguish between the two remaining cases
is whether or not the second argument is an
atom. The frst argument must be a list.
Yes, we can!
(defne equal ?
(lambda ( s1 s2)
(LLnd
Yes.
((and ( atom? s1 ) ( atom? s2) )
( eqan? s1 s2) )
¸ ¸L1 ( atom? s1 ) ( atom? s2) )
#f )
(else ( eqlist ? s1 s2) ) ) ) )
The questions cover all four possible cases.
(defne eqlist ?
(lambda ( l 1 l2)
(LLnd
( ( and ( null ? l1 ) ( null ? l2) ) #t )
¸ ¸L1 ( null ? l1 ) ( null? l2) ) #f )
(else
(and ( equal ? ( car l1 ) ( car l2) )
( eqlist ? ( cdr l 1 ) ( cdr l2) ) ) ) ) ) )
93
The Sixth Commandment
Simplif only aer the function is correct.
Here is rmber after we replace lat by a list l
of Sexpressions and a by any Sexpression.
(defne rmber
(lambda ( s l)
(cond
( ( null ? l) (quote ( ) ) )
( ( atom? ( car l ) )
(cond
( ( equal? ( car l) s) ( cdr l ) )
(else ( cons ( car l)
( rmber s ( cdr l ) ) ) ) ) )
(else (cond
( ( equal ? ( car l) s) ( cdr l ) )
(else ( cons ( car l)
( rmber s
( cdr l ) ) ) ) ) ) ) ) )
Can we simplify it?
And how does that difer?
Is rmber a "star" function now?
Why not ?
Can rmber be further simplifed?
94
Obviously!
(defne rmber
(lambda (s l)
(cond
( ( null ? l) (quote ( ) ) )
(else (cond
( ( equal ? ( car l) s) ( cdr l ))
(else ( cons ( car l)
( rmber s
( cdr l ) ) ) ) ) ) ) ) )
The function rmber now removes the frst
matching Sexpression ö in l, instead of the
frst matching atom a in lat.
No.
Because rmber recurs with the cdr of l only.
Yes, the inner ( cond . . . ) asks questions that
the outer ( cond . . . ) could ak!
Chapter 5
Do it !
Does this new defnition look simpler?
And does it work j ust as well?
Simplify insertL*
When functions are correct and
welldesigned, we can think about them
easily.
Can all functions that use eq? and = be
generalized by replacing eq' and = by the
function equal ?
*Oh My Gawd
*
: It 's Fll of Stars
(defne rmber
(lÜbda ( s l)
(cond
( ( null ? l) (quote ( ) ) )
( ( equal? ( car l) s) ( cdr l ) )
(else ( cons ( car l)
( rmber s ( cdr l ) ) ) ) ) ) )
Yes, i t does!
Yes, because we knew that all the cases and
all the recursions were right before we
simplifed.
We can' t. Before we can ask ( eq' ( car l) old)
we need to know that ( car l) is an atom.
And that saved us this time from getting it
wrong.
Not quite; this won' t work for eqan?, but will
work for all others. In fact , disregarding the
trivial example of eqan', that is exactly what
we shall assume.
95
(E
�
d
�
l@
Is 1 Ü arithmetic expression?
Is 3 an arithmetic expression?
Is 1 + 3 an arithmetic expression?
Is 1 + 3 ? 4 an arithmetic expression?
Is cookie an arithmetic expression?
And, what about 3 t y + 5
What is an arithmetic expression in your
words?
What is (quote a)
What is (quote +)
What does (quote ? ) stand for?
Is ( eqP (quote a) ç)true or false
where ç is a
Is ( eqP x ç) true or false
where x is a
and
çis a
Shadows
Yes.
Yes, of course.
Yes!
Defnitely.
Yes. Are you almost ready for one?
Yes.
In ours:
"For the purpose of this chapter, an
arithmetic expression is either an atom
(including numbers) , or two arithmetic
expressions combined by +, ? ¿ or t. "
a.
The atom +, not the operation + .
The atom ? ¿ not the operation ? .
Tue.
That ' s the same question again. And the
answer is still true.
97
Is ¸ n + 3) an arithmetic expression?
Could we think of ¸ n + 3) Ü an arithmetic
expression?
What would you call ¸ n + 3)
Why is ¸ n + 3) a good representation?
Tue or false: ( numberd? x)
where x is 1
How do you represent 3 + 4 7 5
Tue or false: ( numberd? y)
where y is (3 + (4 t 5) )
Tue or false: ( numberd? Z)
where Z is (2 7 sausage)
What is numberd?
98
Not really, since there are parentheses
around n + 3. Our defnition of arithmetic
expression does not mention parentheses.
Yes, if we keep in mind that the parentheses
are not really there.
We call it a representation for n + 3.
Because
1. ¸ n + 3) is an Sexpression.
It can therefore serve Ü an argument for a
function.
2. It structurally resembles n + 3.
Tue.
(3 + (4 ? 5) ) .
Tue.
False, because sausage is not a number.
It is a function that determines whether Ü
representation of an arithmetic expression
contains only numbers besides the +, 7 ¿
and t.
Chapter 6
Now can you write a skeleton for numberd?
What is the frst question?
What is ( eq? ( car ( cdr aex)) (quote +) )
Ca you guess the third one?
And you must know the fourth one.
Should we ak another question about aexp
Why do we ak four, instead of two,
questions about arithmetic expressions?
After all , arithmetic expressions like (1 + 3)
are lats.
Shadows
(defne numberd?
(lambda ( aexp)
(cond
(
¯¯
(
'
(
is a good guess.
( atom? aex ) .
)
)
)
) ) ) )
It i s the second question.
( eq? ( car ( cdr aex) ) (quote 7 ) ) is perfect .
( eq? ( car ( cdr aexp) ) (quote ¡) ) , of course.
No! So we could replace the previous
question by else.
Because we consider (1 + 3) as a
representation of an arithmetic expression in
list form, not a a list itself. And, an
arithmetic expression is either a number, or
two arithmetic expressions combined by +,
7 ¿ or t.
99
Now you can almost write numberd?
Why do we ask ( number? aex) when we
know that aex is an atom?
What do we need to know if the aexp consists
of two arithmetic expressions combined by +
In which position is the frst subexpression?
In which position is the second
subexpression?
So what do we need to ask?
What is the second answer?
100
Here is our proposal:
(defne numberd?
(lambda ( aex)
(cond
( ( atom? aexp) ( number? ae))
( ( eq? ( car ( cdr aex) ) (quote +) )
. . . )
( ( eq? ( car ( cdr aex)) (quote ?) )
. . . )
( ( eq? ( car ( cdr aex) ) (quote t) )
. . . ) ) ) )
Because we want t o know i f all arithmetic
expressions that are atoms are numbers.
We need to fnd out whether the two
subexpressions are numbered.
It is the car of aex.
It is the car of the cdr of the cdr of aex.
( numberd? ( car aex)) and
( numberd? ( car ( cdr ( cdr aex) ) ) ) .
Both must be true.
(and ( numberd? ( car aex) )
( numberd? ( car ( cdr ( cdr aex) ) ) ) )
Chapter 6
Ty numberd? again.
Since aex wa already understood to be an
arithmetic expression, could we have written
numberd? in a simpler way?
Why can we simplify?
What is ( value u)
where u is 13
( value x)
where
J is (1 + 3)
Shadow
(defne numberd?
(lambda ( aex)
(cond
( ( atom? aex) ( number? aex) )
( ( eq? ( car ( cdr aexp) ) (quote +) )
(and ( numberd? ( car aexp) )
( numberd?
( car ( cdr ( cdr aex) ) ) ) ) )
( ( eq? ( car ( cdr aex) ) (quote 7 ) )
( and ( numberd? ( car aex) )
( numberd?
( car ( cdr ( cdr aex) ) ) ) ) )
( ( eq? ( car ( cdr aex) ) (quote t) )
(and ( numberd? ( car aex) )
( numberd?
( car ( cdr ( cdr aex) ) ) ) ) ) ) ) )
Yes:
(defne numberd?
(lambda ( aex)
(cond
( ( atom? aex) ( number? aexp) )
(else
(and ( numberd? ( car aex) )
( numberd?
( car ( cdr ( cdr aex) ) ) ) ) ) ) ) )
Because we know we' ve got the function
right .
13.
4.
101
( value y)
where
y is (1 + (3 ¡ 4) )
( value Z)
where Z is cooki e
( value nex) returns what we think is the
natural value of a numbered arithmetic
expression.
82.
No answer.
We hope.
How many questions does value ak about Four.
nexp
Now, let ' s attempt to write value
What is the natural value of an arithmetic
expression that is a number?
What is the natural value of an arithmetic
expression that consists of two arithmetic
expressions combined by +
Can you think of a way to get the value of
the two subexpressions in ( 1 + (3 7 4) )
102
(defne value
(lambda ( nex)
(cond
( ( atom? nex) . . . )
( ( eq? ( car ( cdr nex)) (quote +) )
. . . )
( ( eq? ( car ( cdr nex)) (quote 7 ) )
. . . )
(else . . . ) ) ) )
It i s j ust that number.
If we had the natural value of the two
subexpressions, we could j ust add up the two
values.
Of course, by applying value to 1 , and
applying value to (3 7 4) .
Chapter 6
And in general? By recurring with value on the
subexpressions.
The Seventh Commandment
Recur on the subparts that are of the same nature:
• On the sublists of a list.
• On the subexpressions of an arithmetic expression.
Give value another try.
Ca you think of a diferent representation of
arithmetic expressions?
Could (3 4 +) represent 3 + 4
Could ¸ + 3 4)
Or (pl us 3 4)
Shadows
(defne value
(lambda ( nex)
(cond
( ( atom? nex) nex)
( ( eq? ( car ( cdr nexp) ) (quote +))
( + ( value ( car nex) )
( value ( car ( cdr ( cdr nex) ) ) ) ) )
( ( eq? ( car ( cdr nex) ) (quote 7 ) )
( 7 ( value ( car nex ) )
( value ( car ( cdr ( cdr nex) ) ) ) ) )
(else
( ¡ ( value ( car nexp) )
( value
( car ( cdr ( cdr nexp) ) ) ) ) ) ) ) )
There are several of them.
Yes.
Yes.
Yes.
103
Is ( + ¸ 7 3 6) (t 8 2) ) a representation of an
arithmetic expression?
Ty to write the function value for a new
kind of arithmetic expression that is either:
 a number
 a list of the atom + followed by
two arithmetic expressions,
 a list of the atom 7 followed by
two arithmetic expressions, or
 a list of the atom t followed by
two arithmetic expressions.
You guessed it.
Let ' s try an example.
( atom? nex)
where
nexp is ( + 1 3)
( eq? ( car nex) (quote +) )
where
nex is ( + 1 3)
And now recur.
What is ( cdr nex)
where
nex is ( + 1 3)
104
Yes.
What about
(defne vlue
(lambda ( nex)
(cond
( ( atom? nex) nex)
( ( eq? ( car nex) (quote +) )
( + ( value ( cdr nex) )
( value ( cdr ( cdr nex) ) ) ) )
( ( eq? ( car nex) (quote 7) )
( 7 ( value ( cdr nex))
( value ( cdr ( cdr nex) ) ) ) )
(else
(t ( value ( cdr nex ) )
( value ( cdr ( cdr nexp) ) ) ) ) ) ) )
It' s wrong.
(+ 1 3) .
No.
Yes.
Yes.
( 1 3) .
Chapter 6
(1 3) is not our representation of an
arithmetic expression.
How can we get the frst subexpression of a
representation of an arithmetic expression?
Is ( cdr ( cdr nex)) an arithmetic expression
where
nex is ¸ + 1 3)
Again, we were thinking of the list ( + 1 3)
instead of the representation of an arithmetic
expression.
What do we mean if we say the car of the
cdr of nex
Let 's write a function 1stsubex for
arithmetic expressions.
Why do we ask else
Can we get by without ( cond . . . ) if we
don' t need to ask questions?
Shadows
No, we violated The Seventh Commandment .
(1 3) is not a subpart that is a representation
of an arithmetic expression! We obviously
recurred on a list . But remember, not all lists
are representations of arithmetic expressions.
We have to recur on subexpressions.
By taking the car of the cdr.
No, the cdr of the cdr is (3) , and (3) is not
an arithmetic expression.
Taking the car of the cdr of the cdr gets us
back on the right track.
The frst subexpression of the representation
of an arithmetic expression.
(defne 1stsubex
(lambda ( aex)
(cond
(else ( car ( cdr aex) ) ) ) ) )
Because the frst question i s also the last
question.
Yes, remember oneliners from chapter 4.
(defne 1stsubex
(lambda ( aex)
( car ( cdr aexp) ) ) )
105
Write 2ndsubex for arithmetic expressions.
Finally, let ' s replace ( car nexp) by
( opertor nex)
Now write value again.
Can we use this value function for the frst
representation of arithmetic expressions in
this chapter?
Do it !
106
(dÜfne 2ndsubex
(lambda ( aex)
( car ( cdr ( cdr aex) ) ) ) )
(defne opertor
(lambda ( aex)
( car aex) ) )
(defne value
(lambda ( nex)
(cond
( ( atom? nex) nex)
( ( eq? ( opertor nex) (quote +) )
( + ( value ( 1 stsubex nex))
( value ( 2ndsubex nex) ) ) )
( ( eq? ( opertor nex) (quote 7 ) )
( 7 ( value ( 1 stsubex nex))
( value ( 2ndsub ex nex) ) ) )
(else
( ¡ ( value ( 1stsubex nex) )
( value ( 2ndsubex nex) ) ) ) ) ) )
Yes, by changing 1stsubex ad opertor.
(defne 1stsub ex
(lambda ( aex)
( car aexp) ) )
¸defne opertor
(lambda ( aex)
( car ( cdr aex) ) ) )
Chapter 6
Wan' t this eay? Yes, because we used help functions to hide
the representation.
The Eighth Commandment
Use help functions to abstract from representations.
Have we seen representations before?
For what entities have we used
representations?
Numbers are representations?
What else could we have used?
Do you remember how many primitives we
need for numbers?
Let' s try another representation for numbers.
How shall we represent zero now?
How is one represented?
How is two represented?
Shadows
Yes, we j ust did not tell you that they were
representations.
Tuthvalues! Numbers!
Yes. For example 4 stands for the concept
four. We chose that symbol because we are
accustomed to arabic representations.
( () () () ( ) ) would have served j ust as well .
What about ( ( ( ( ( ) ) ) ) ) ? How about ¸  V)?
Four: number?, zer?, add1 , and sub1 .
() is our choice.
( ( ) ) .
( ( ) ( ) ) .
107
Got it? What ' s three?
Write a function to test for zero.
Can you write a function that is like add1
What about sub1
Is this correct?
What is ( zub1 n) where n is ( )
Rewrite + using this representation.
Ha the defnition of + changed?
108
Three is ( ( ) ( ) ( ) ) .
(defne ser?
(lambda ( n)
( null? n) ) )
(defne edd1
(lambda ( n)
( cons (quote ( ) ) n) ) )
(defne zub1
(lambda ( n)
( cdr n) ) )
Let ' s see.
No answer, but that ' s fne.
 Recall The Law of Cdr.
(defne +
(lambda ( n M)
(cond
( ( ser? M) n)
(else ( edd1 ( + n ( zub1 m) ) ) ) ) ) )
Yes and no. It chaned, but only slightly.
Chapter 6
Recal lat ?
Do you remember what the value of ( lat ? ls)
is where l is (1 2 3)
What is ¸ I2 3) with our new numbers?
What is ( lat? ls) where
ls is
' ' '
) ) ( ( )
'
) ) ( ( )
'
) ( ) ) )
Is that bad?
Shadows
Easy:
(defne lat ?
(lambda (l)
(cond
( ( null ? l) #t )
( ( atom? ( car l ) ) ( lat? ( cdr l ) ) )
(else #f ) ) ) )
But why did you ask?
#t g of course.
( ( ( ) ) ( ( ) ( ) ) ( ( ) ( ) ( ) ) ) .
It is very false.
You must beware of shadows.
109
�
l � � f� ���
Is this a set?
(appl e peaches appl e pl um)
Tue or false: ( set ? lat)
where
lat is (appl es peaches pears pl ums)
How about ( set ? lat)
where
lat is ( )
Ty t o write set ?
Simplify Iet ?
Does this work for the example
(appl e 3 pear 4 9 appl e 3 4}
Were you surprised to see the function
member? appear in the defnition of set ?
Fiends and Relations
No, since appl e appears more than once.
#t , because no atom appears more than
once.
#t , because no atom appears more than
once.
( defne set ?
(lambda ( lat)
(cond
( ( null ? lat) #t )
(else
(cond
( ( member? ( car lat) ( cdr lat) )
#f )
(else ( set ? ( cdr lat ) ) ) ) ) ) ) )
(defne set ?
(lambda ( lat)
(cond
( ( null ? lat) #t )
( ( member? ( car lat) ( cdr lat) ) #f )
(else ( set? ( cdr lat ) ) ) ) ) )
Yes, since member? i s now written using
equal ? instead of eq?.
You should not be, because we have written
member? already, and now we can use it
whenever we want .
1 1 1
What is ( makeset lat)
where
lat is (appl e peach pear peach
pl um appl e l emon peach)
Ty to write makeset using member?
Are you surprised to see how short this is?
Using the previous defnition, what is the
result of ( makeset lat)
where
lat is (appl e peach pear peach
pl um appl e l emon peach)
Ty to write makeset using multirmber
What is the result of ( makeset lat) using this
second defnition
where
lat is (appl e peach pear peach
pl um appl e l emon peach)
112
(appl e peach pear pl um l emon) .
(defne makeset
(lambda ( lat)
(cond
( ( null? lat) (quote ( ) ) )
( ( member? ( car lat) ( cdr lat) )
( makeset ( cdr lat) ) )
(else ( cons ( car lat)
( makeset ( cdr lat) ) ) ) ) ) )
We hope so. But don' t be afraid: it ' s right.
(pear pl um appl e l emon peach) .
(defne makeset
(lambda ( lat)
(cond
( ( null ? lat) (quote ( ) ) )
(else ( cons ( car lat)
( makeset
( multirmber ( car lat)
( cdr lat ) ) ) ) ) ) ) )
( appl e peach pear pl um l emon) .
Chapter 7
Describe in your own words how the second
defnition of makeset works.
Does the second makeset work for the
example
(appl e 3 pear 4 9 appl e 3 4)
What is ( subset ? set1 set2)
where
set1 is (5 chi cken wi ngs)
and
set2 is (5 hamburgers
2 pi eces fried chi cken and
l i ght duckl i ng wi ngs)
What is ( subset? set1 set2)
where
set1 is (4 pounds of horseradi sh)
and
set2 is (four pounds chi cken and
5 ounces horseradi sh)
Write subset?
Fends and Relations
Here are our words:
"The function makeset remembers to cons
the frst atom in the lat onto the result of
the natural recursion, ater removing all
occurrences of the frst atom from the rest
of the lat . "
Yes, since multirember is now written using
equal? instead of eq?.
#t , because each atom in set1 is also in set2.
#f.
(defne subset ?
(lambda ( set1 set2)
(cond
( ( null ? set1 ) #t )
(else (cond
( ( member? ( car set1 ) set2)
( subset? ( cdr set1 ) set2) )
(else #f ) ) ) ) ) )
1 13
Can you write a shorter version of subset ?
Ty to write subset ? with (and . . . )
What is ( eqset ? set1 set2)
where
set1 is (6 l arge chi ckens with wi ngs)
and
set2 is (6 chi ckens wi th l arge wi ngs)
Write eqset ?
Can you write eqset ? with only one
condline?
1 14
(defne subset?
(lambda ( set1 set2)
(cond
( ( null ? set1 ) #t )
( ( member? ( car set1 ) set2}
( subset ? ( cdr set1 ) set2) )
(else #f ) ) ) )
(defne subset ?
(lambda ( set1 set2)
(cond
( ( null ? set1 ) #t )
(else
(and ( member? ( car set1 ) set2)
( subset ? ( cdr set1 ) set2) ) ) ) ) )
#t .
(defne eqset ?
(lambda ( set1 set2)
(cond
( ( subset ? set1 set2)
( subset? set2 set1 ) )
(else #f ) ) ) )
(defne eqset ?
(lambda ( set1 set2)
(cond
(else (and ( subset? set1 set2)
( subset? set2 set1 ) ) ) ) ) )
Chapter 7
Write the oneliner.
What is ( intersect? set1 set2)
where
set1 is (stewed tomatoes and macaroni )
and
set2 is ( macaroni and cheese)
Defne the function intersect?
Write the shorter version.
Ty writing intersect? with ¸LÏ   . )
Fiends and Relations
(defne eqset ?
(lambda ( set1 set2)
#t ,
(and ( subset ? set1 set2)
( subset ? set2 set1 ) ) ) )
because at least one atom in set1 is in
set2.
(defne intersect?
(lambda ( set1 set2)
(LLnd
( ( null ? set1 ) #f )
(else
(LLnd
( ( member? ( car set1 ) set2) #t )
(else ( intersect ?
( cdr set1 ) set2) ) ) ) ) ) )
(defne intersect?
(lambda ( set1 set2)
(LLnd
( ( null ? set1 ) #f )
( ( member? ( car set1 ) set2) #t )
(else ( intersect? ( cdr set1 ) set2) ) ) ) )
(defne intersect ?
(lambda ( set1 set2)
(LLnd
( ( null ? set1 ) #f )
(else ¦LÏ ( member? ( car set1 ) set2)
( intersect?
( cdr set1 ) set2) ) ) ) ) )
Compare subset? and intersect ?.
115
What is ( intersect set1 set2)
where
set1 is (stewed tomatoes and macaroni )
and
set2 is ( macaroni and cheese)
Now you can write the short version of
intersect
What is ( union set1 set2)
where
set1 is (stewed tomatoes and
macaroni casserol e)
and
set2 is ( macaroni and cheese)
Write union
1 16
(and macaroni ) .
(defne intersect
(lambda ( set1 set2)
(cond
( ( null? set1 ) (quote ( ) ) )
( ( member? ( cr set1 ) set2)
( cons ( car set1 )
( intersect ( cdr set1 ) set2) ) )
(else ( intersect ( cdr set1 ) set2)))))
(stewed tomatoes casserole macaroni
and cheese)
(defne union
(labda ( set1 set2)
(cond
( ( null ? set1 ) set2)
( ( member? ( car set1 ) set2)
( union ( cdr set1 ) set2) )
(else ( cons ( car set1 )
( union ( cdr set1 ) set2))))))
Chapter 7
What is this function?
(defne J
(lambda ( set1 set2)
(cond
( ( null ? set1 ) (quote ( ) ) )
( ( member? ( car set1 ) set2)
( J ( cdr set1 ) set2) )
(else ( cons ( car set1 )
( J ( cdr set1 ) set2) ) ) ) ) )
What i s ( intersect all lset)
where
lset is ( ¸a b c) ( c a d e) ( e f g h a b) )
What i s ( intersect all lset)
where
lset is ¸( 6 pears and)
(3 peaches and 6 peppers)
(8 pears and 6 pl ums)
(and 6 prunes wi th some appl es) )
Now, using whatever help functions you
need, write intersectall asuming that the list
of sets is nonempty.
Is this a pair?1
¸pear pear)
1 A pair in Scheme (or Lisp) is a diferent but related object.
Fiends and Relations
In our words:
"It is a function that returns all the atoms
in set1 that are not in set2. "
That is, J is the ¸set) diference function.
(a) .
(6 and) .
(defne intersectall
(lambda ( lset)
(cond
( ( null ? ( cdr lset ) ) ( car lset ) )
(else ( intersect ( car lset)
( intersectall ( cdr lset ) ) ) ) ) ) )
Yes, because i t i s a list with only two atoms.
117
Is this a pair?
(3 7)
Is this a pair?
((2) ( pai r) )
( apair? l)
where
l is (ful l (house))
Defne apair?
How can you refer to the frst Sexpression of
a pair?
How can you refer to the second Sexpression
of a pair?
How can you build a pair with two atoms?
How can you build a pair with two
Sexpressions?
Did you notice the diferences between the
last two answers?
1 18
Yes.
Yes, because it is a list with only two
Sexpressions.
#t ,
because it is a list with only two
Sexpressions.
(defne apair?
(lambda (x)
(cond
( ( atÛm? x) #f )
( ( Hull ? x) #f )
( ( Hull ? ( Ldr x) ) #f )
( ( Hull ? ( Ldr ( Ldr x) ) ) #t )
(else #f ) ) ) )
By taking the car of the pair.
By taking the car of the cdr of the pair.
You LÛHb the frst one onto the LÛHb of the
second one onto ( ) o That is,
¸ LÛHb x1 ¸ LÛHb x2 (quote () ) ) ) .
You LÛHb the frst one onto the LÛHb of the
second one onto ( ) . That is,
¸ LÛHb x1 ¸ LÛHb x2 (quote ( ) ) ) ) .
No, there aren' t any.
Chapter 7
(defne frst
(lambda ¸py
(cond
(else ( car p) ) ) ) )
(defne second
(lambda ¸py
(cond
(else ( car ( cdr py y y y y y
(defne build
(lambda ( sl s2)
(cond
¸else ( cons sl
( cons s2 (quote ( ) ) ) ) ) ) ) )
What possible uses do these three functions
have?
Ca you write thir Ü a oneliner?
Is l a rei where
l is (appl es peaches pumpki n pi e)
Is l a rei where
l is ( (appl es peaches)
( pumpki n pi e)
(appl es peaches) )
Is l a rei where
l is ( ( appl es peaches) ( pumpki n pi e) )
Is l a rei where
l is ¸ ¸43) ¸42) (7 6) (6 2) (3 4) )
Fiends and Relations
They are used to make representations of
pairs and to get parts of representations of
pairs. See chapter 6.
They will be used to improve readability,
as you will soon see.
Redefne frst, second, and build as
oneliners.
¸defne thir
(lambda ¸ l )
( car ( cdr ( cdr l ) ) ) ) )
No, since l i s not a list of pairs. We use rei to
stand for relation.
No, since l is not a set of pairs.
Yes.
Yes.
119
Is rl a fun
where
rl is ((4 3) (4 2) (7 6) (6 2) (3 4) )
What i s (fn? rl)
where
rl is ( ( 8 3) (4 2) (7 6) (6 2) (3 4) )
What i s (fn? rl)
where
rl is ( ( d 4) (b 0) (b 9) (e 5) (g 4) )
Write fn? with set ? and frsts
Is fn? a simple oneliner?
How do we represent a fnite function?
What is ( rvrel rl)
where
rl is ( (8 a) ( pumpki n pi e) (got si ck) )
You can now write rvrl
120
No. We use fun to stand for function.
#t , because (frsts rl) is a set
See chapter 3.
#f, because b is repeated.
(defne fn?
(lambda ( rl)
(set? (frsts rl) ) ) )
It sure is.
For us, a fnite function is a list of pairs in
which no frst element of any pair is the same
Ü any other frst element .
¸ ¸a 8) (pi e pumpki n) (si ck got ) ) .
(defne rvrl
(lambda ( rl)
(cond
( ( null? rl) (quote ( ) ) )
(else ( cons ( build
(second ( car rl) )
(frst ( car rl) ) )
( rvrl ( cdr rl) ) ) ) ) ) )
Chapter 7
Would the following also be correct:
(defne rvrl
(lambda ( rl)
(cond
( ( null ? rl) (quote ( ) ) )
(else ( cons ( cons
( car ( cdr ( car rl) ) )
( cons ( car ( car rl) )
(quote ( ) ) ) )
( rvrl ( cdr rl) ) ) ) ) ) )
Suppose we had the function rvpair that
reversed the two components of a pair like
this:
(defne rvpair
(lambda (pair)
( build (second pair) (frst pair) ) ) )
How would you rewrite rvrl to use this help
function?
Ca you guess why fn is not a fullfun
where
fn is ( (8 3) (4 2) (7 6) (6 2) (3 4) )
Why is #t the value of (fllfn? fn)
where
fn is ( (8 3) (4 8) (7 6) (6 2) (3 4) )
What is (fllfn ' fn)
where
fn is ( (grape raisi n)
( pl um prune)
(stewed prune) )
Fiends and Relations
Yes, but now do you see how representation
aids readability?
No problem, and it is even easier to read:
¸defne revrl
(lambda ( rl)
¦cond
( ( null ? rl) (quote ( ) ) )
¸else ( cons ( rvpair ( car rl) )
( rvrl ( cdr rl) ) ) ) ) ) )
fn i s not a fullfun, since the 2 appears more
than once as a second item of a par.
Because (3 8 6 2 4) is a set .
#f.
121
What is (fullfn? fn)
where
fn is ( (grape rai si n)
( pl um prune)
(stewed grape))
Defne fllfn?
Can you defne seconds
What is another name for fllfn?
Can you think of a second way to write
oneto one ?
Is ((chocol ate chi p) (doughy cooki e)) a
onetoone function?
#t , because ( rai si n prune grape) is a set.
(defne fllfn?
(lambda (fn)
(set? (seconds fn) ) ) )
It i s j ust like frsts .
onetoone ?.
(defne oneto one ?
(lambda (fn)
(fn? ( rvrl fn) ) ) )
Yes, and you deserve one now!
Go and get one!
122 Chapter 7
Lr UCttCr ÿet , uake ÿour own.
(defne cookies
(lÜbda ( )
Fiends ad Relations
( bake
(quote (350 degrees) )
(quote ( 12 mi nutes))
( mix
(quote (wal nuts 1 cup))
(quote (chocol atechi ps 16 ounces))
( mix
( mix
(quote (flour 2 cups))
(quote (oatmeal 2 cups) )
(quote (sal t .5 teaspoon) )
(quote (baki ng poder 1 teaspoon) )
(quote (baki ngsoda 1 teaspoon) ) )
( mix
(quote (eggs 2 l arge) )
(quote (vani l la 1 teaspoon))
( cram
(quote (butter 1 cup))
(quote (sugar 2 cups) ) ) ) ) ) ) ) )
123
Remember what we did in rmber and
inserlL at the end of chapter 5?
Ca you write a function rmbert that
would use either eq? or equal ?
How ca you make rmber remove the frst a
from (b c a)
How can you make rmber remove the frst c
from (b c a)
How can you make rmbert use equal ?
instead of eq?
What is ( rmbert test ? a l)
where
test? is =1
a is 5
and
l is (6 2 5 3)
' L: (remberf (fuction •) 5 ' (6 2 5 3) ) ,
but there is more.
What is ( rmbert test? a l)
where
test? is eq?
a is jel l y
and
l is Uel l y beans are good)
And what i s ( rmbert test? a l )
where
test ? is equal ?
a is ( pop corn)
and
l is ( l emonade (pop corn) and (cake) )
Lambda the Utimate
We replaced eq? with equal?
No, because we have not yet told you how.
By passing a and (b c a) as arguments to
rmber.
By passing c and (b c a) as arguments to
rmber.
By passing equal? a an argument to
rmbert.
(6 2 3) .
( beans are good) .
( l emonade and (cake) ) .
125
Try to write rmberf
What about the short version?
How does ( remberf test ? a l) act
where test? is eq?
And what about ( rmberf test? a l)
where test? is equal?
Now we have four functions that do almost
the same thing.
126
(defne rmberf
(lambda ( test ? a l)
(cond
( ( null ? l) (quote ( ) ) )
(else (cond
( ( test ? ( car l) a)
1
( cdr l ))
(else ( cons ( car l)
( rmberf test ? a
( cdr l ) ) ) ) ) ) ) ) )
This i s good!
1
L: (fucall test? (car 1) a) . Use funcall when
invoking a function argument or a function that ha not
been defued.
(defne rmberf
(lambda ( test ? a l)
(cond
( ( null ? l) (quote ( ) ) )
( ( test? ( car l) a) ( cdr l ))
(else ( cons ( car l)
( rmberf test ? a
( cdr l ) ) ) ) ) ) )
( rmberf test? a l )
where test? i s eq?, acts like rmber.
This is j ust rmber with eq? replaced by
equal ?.
Yes:
rmber with =
rmber with equal ?
rmber with eq?
and
rmberf.
Chapter 8
And rmberf ca behave like all the others.
What kind of values can functions return?
What about functions themselves?
Ca you say what (lambda ¸ Ú l) . . . ) is?
Now what is
(lambda ¸ Ú)
(lambda ¸J)
( eq? J Ú) ) )
Is this called "Currying?"
It is not called "Schonfnkeling. "
Using (defne . . . ) give the preceding
function a name.
What is ( eq?c k)
where k is sal ad
Lambda the Ultimate
Let ' s generate all versions with rmberf.
Lists and atoms.
Yes,
but you probably did not know that yet .
(lambda ¸ Ú l) . . . ) is a function of two
arguments, Ú and l .
It i s a function that, when passed an
argument Ú¿ returns the function
(lambda ¸J)
( eq? J Ú) )
where Ú i s j ust that argument .
Thank you, Moses Schonfnkel
( 18891942) .
Thank you, Hakell B. Curry
( 19001982) .
(defne eq?c1
(lambda ¸ Ú)
(lambda ¸ J)
( eq? J Ú) ) ) )
This i s our choice.
1 L: (defu eq?c (a)
(fuction
(labda (x)
(eq x a) ) ) )
Its value is a function that takes J a an
argument and tests whether it is eq? to sal ad.
127
So let ' s give it a name using (defne . . . )
I (defne
1
eq?salad ( eq?c k))
where k i s sal ad
1
L: ( setq eq?salad (eq?c ' salad) } .
Use setq to defne a function that can be fucalled.
What is ( eq? salad y)
1
where y is sal ad
1
L: (fucall eq?salad y) , since eq?salad ha not been
defued.
And what is ( eq?salad y)
where y is tuna
Do we need to give a name to eq?salad
Now rewrite rmbert as a function of one
argument test? that returns an argument like
rmber with eq? replaced by test ?
128
Okay.
#t .
#
f.
No, we may just as well ak
( ( eq?c x) y)
1
where
x is sal ad
and
y is tuna.
1
L: (fucall (eq?c x) y) , since (eq?c x) i s a function
that ha not been defued.
(defne rmbert
(lambda ( test ?)
(lambda ( a l)
(Cond
( ( null ? l) (quote ( ) ) )
( ( test ? ( car l) a) ( cdr l ) )
(else ( cons ( car l) . . . ) ) ) ) ) )
i s a good start.
Chapter 8
Describe in your own words the result of
( rmberf test ?)
where
test? is eq?
Give a name to the function returned by
( rmberf test ?)
where
test? is eq?
What is ( rmbereq? a l)
where a is tuna
and
l is (tuna sal ad is good)
Did we need to give the name rmbereq? to
the function ( rmberf test ?)
where
test? is eq?
Now, complete the line
( cons ( car l) . . . )
in rmberf so that rmberf works.
What is ( ( rmberf eq?) a l)
where Û is tuna
and
l is (shri mp sal ad and tuna sal ad)
Lambda the Ultimate
It is a function that takes two arguments, a
and l. It compares the elements of the list
with a, and the frst one that is eq? to a is
removed.
(defne rmbereq? ( rmberf test ?) )
where
test ? is eq?.
(sal ad is good) .
No, we could have written
( ( rmberf test ?) a l)
where
test? is eq?
a is tuna
and
l is (tuna sal ad i s good) .
(defne rmberf
(lambda ( test ?)
(lambda ( a l)
(cond
( ( null ? l) (quote ( ) ) )
( ( test ? ( car l) a) ( cdr l ) )
(else ( cons ( car l)
( ( rmberf test ?) a
( cdr l ) ) ) ) ) ) ) )
(shri mp sal ad and sal ad) .
129
What is ( ( rmberf eq?) a l)
where a is eq?
and
l is (equal ? eq? eqan? eql i st? eqpai r?) 1
¯ Did you notice the diference between eq? and eq?
Remember that the former is the atom and the latter is the
function.
And now transform insertL to insertLf the
same way we have transformed rmber into
rmberf
And, j ust for the exercise, do it to insertR
Are insertR and insertL similar?
Can you write a function insertg that would
insert either at the left or at the right?
130
(equal ? eqan? eql i st? eqpai r?) .
(defne insertLf
(lambda ( test ?)
(lambda ( new old l)
(cond
( ( null ? l) (quote ( ) ) )
( ( test ? ( car l) old)
( cons new ( cons old ( cdr l ) ) ) )
(else ( cons ( car l )
( ( insertLf test ?) new old
( cdr l ) ) ) ) ) ) ) )
(defne insertRf
(lambda ( test ?)
(lambda ( new old l)
(cond
( ( null? l) (quote ( ) ) )
( ( test ? ( car l) old)
( cons old ( cons new ( cdr l ) ) ) )
(else ( cons ( car )
( ( insertRf test ?) new old
( cdr l ) ) ) ) ) ) ) )
Only the middle piece i s a bit diferent .
If you can, get yourself some cofee cake and
relax! Otherwise, don' t give up. You' ll see it
in a minute.
Chapter 8
Which pieces difer?
Put the diference in words!
So how can we get rid of the diference?
Defne a function seqL that
1. takes three arguments, and
2. conses the frst argument
onto the result of consing
the second argument onto
the third argument.
What is:
(defne seqR
(lambda ( new old l)
( cons old ( cons new l ) ) ) )
Do you know why we wrote these functions?
Lambda the Ultimate
The second lines difer from each other. In
insertL it is:
( ( eq? ( car l) old)
( cons new ( cons old ( cdr l ) ) ) ) ,
but in insertR it is:
( ( eq? ( car l) old)
( cons old ( cons new ( cdr l ) ) ) ) .
We say:
"The two functions cons old and new in a
diferent order onto the cdr of the list l . "
You probably guessed it: by passing i n a
function that expresses the appropriate
consing.
(defne seqL
(lambda ( new old l)
( cons new ( cons old l ) ) ) )
A function that
1 . takes three arguments, and
2. conses the second argument
onto the result of consing
the frst argument onto
the third argument.
Because they express what the two difering
lines in insertL and insertR express.
131
Ty to write the function insertg of one
argument seq
which returns insertL
where seq is seqL
and
which returns insertR
where seq is seqR
Now defne insertL with insertg
And insertR.
Is there something unusual about these two
defnitions?
Is it necessary to give names to seqL and
seqR
Defne insertL again with insertg
Do not pass in seqL this time.
132
(defne insertg
(lambda (seq)
{lambda ( new old l)
(Lond
( ( null ? l) (quote ( ) ) )
( ( eq? ( car l) old)
(seq new old ( cdr l ) ) )
(else ( cons ( car l)
( ( insertg seq) new old
( cdr l ) ) ) ) ) ) ) )
(defne insertL ( insertg seqL) )
(defne insertR ( insertg seqR))
Yes. Earlier we would probably have written
(defne insertL ( insertg seq))
where
seq is seqL
and
(defne insertR ( insertg seq))
where
seq is seqR.
But, using "where" is unnecessary when you
pass functions as arguments.
Not really. We could have passed their
defnitions instead.
(defne insertL
( insertg
(lambda ( new old l)
( cons new ( cons old l ) ) ) ) )
Chapter 8
Is this better?
Do you remember the defnition of subst
Does this look familiar?
Defne a function like seqL or seqR for subst
And now defne subst using insertg
And what do you think yyy is
(defne yyy
(lambda ( a l)
( ( insertg seqrm) #f a l ) ) )
where
¸defne seqrm
(lambda ( new old l)
l ))
Lambda the Ultimate
Yes, because you do not need to remember as
many names. You can
( rmber Jnename "yourmind" )
where Jnename is seqL.
Here is one.
(defne subst
(lambda ( new old l)
(cond
( ( null ? l) (quote ( ) ) )
( ( eq? ( car l) old)
( cons new ( cdr l ) ) )
(else ( cons ( car l)
( subst new old ( cdr l ) ) ) ) ) ) )
Yes, i t looks like insertL or insertR. Just the
answer of the second condline is diferent .
What do you think about this?
(defne seqS
(lambda ( new old l)
( cons new l ) ) )
(defne subst ( insertg seqS))
Surprise! It is our old friend rmber
Hint : Step through the evaluation of
( yyy a l)
where
a is sausage
and
l is ( pizza with sausage and bacon) .
What role does #f play?
133
What you have j ust seen is the power of abstraction.
The Ninth Commandment
Abstract common patterns with a new function.
Have we seen similar functions before?
Do you remember value from chapter 6?
Do you see the similarities?
Can you write the function atomtofnction
which:
1 . Takes one argument x and
2. returns the function +
134
if ( eq? x (quote +) )
returns the function 7
if ( eq? x (quote 7) ) and
returns the function t
otherwise?
Yes, we have even seen functions with similar
lines.
(defne value
(lambda ( nex)
(cond
( ( atom? nex) nex)
( ( eq? ( opertor nex)
(quote +) )
( + ( value ( 1stsubex nex))
( value ( 2ndsubex nex) ) ) )
( ( eq? ( opertor nex)
(quote 7 ) )
( 7 ( value ( 1stsubex nex))
( value ( 2ndsubexp nexp) ) ) )
(else
( ¡ ( value ( 1stsubex nex))
( value ( 2ndsubex nex) ) ) ) ) ) )
The lat three answers are the same except
for the +, 7 ¿ and t.
(defne atomtofnction
(lambda (x)
¸cond
( ( eq? x (quote +) ) + )
( ( eq? x (quote 7 ) ) 7 )
¸else ¡) ) ) )
Chapter 8
What is ( atomtofnction ( opertor nexp) )
where
nex is ¸ + 5 3)
Can you use atomtofnction to rewrite
value with only two condlines?
Is this quite a bit shorter than the frst
version?
Time for an apple?
Here is multirmber again.
(defne multirmber
(lambda ( a lat)
(Lond
( ( null ? lat) (quote ( ) ) )
( ( eq? ( car lat) a)
( multirmber a ( cdr lat) ) )
(else ( cons ( car lat)
( multirmber a
( cdr lat ) ) ) ) ) ) )
Write multirmberf
What is ( ( multiremberf test?) a lat)
where
test? is eq?
a is tuna
and
lat is (shri mp sal ad tuna sal ad and tuna)
Lambda the Ultimate
The function +, not the atom +.
Of course.
(defne value
(lambda ( nex)
(cond
( ( atom? nexp) nex)
(else
( ( atom tofnction
( opertor nex) )
( value ( 1 stsub ex nex) )
( value ( 2ndsub exp nex) ) ) ) ) ) )
Yes, but that ' s oky. We haven' t changed its
meaning.
One a day keeps the doctor away.
No problem.
(defne multirmberf
(lambda ( test ?)
(lambda ( a lat)
(Lond
( ( null ? lat) (quote ( ) ) )
( ( test ? a ( car lat ) )
( ( multirmberf test ?) a
( cdr lat ) ) )
(else ( cons ( car lat)
( ( multirmberf test ?) a
( cdr lat) ) ) ) ) ) ) )
(shri mp sal ad sal ad and) .
135
Wasn' t that easy?
Defne multirmber eq? using multirmberf
Do we really need to tell multirmberf
about tuna
Does test ? change as multirmberf goes
through lat
Can we combine a and test?
How would it do that?
Here is one way to write this function.
I
(defne <q?tuno
.
( eq?c k) )
where k i s tuna
Can you think of a diferent way of writing
this function?
Have you ever seen defnitions that contain
atoms?
136
Yes.
(defne multirmbereq?
( multirmberf test?) )
where test? i s eq?.
As multirmberf visits all the elements in
lat , it always looks for tuna.
No, test? always stands for eq?, just a a
always stands for tuna.
Well , test? could be a function of j ust one
argument and could compare that argument
to tuna.
The new test? takes one argument and
compares it to tuna.
Yes, and here i s a diferent way:
(defne eq?tuna
( eq? c (quote tuna) ) )
Yes, 0, (quote 7 ) ¿ (quote +) , and many
more.
Chapter 8
Perhaps we should now write multirmberT
which is similar to multirmberf
Instead of taking testP and returning a
function, multirmberT takes a function like
eq?tuna and a lat and then does its work.
What is ( multirmberT test ? lat)
where
test? is eq?tuna
and
lat is (shri mp sal ad tuna sal ad and tuna)
Is this easy?
How about this?
(defne multirmber&co
(lamda ( a lat col)
(cond
( ( null ? lat)
( col ,
quote ( ) ) (quote ( ) ) ) )
( ( eqP ( car lat) a)
( multirmber&co a
( cdr lat)
(lambda ( newlat seen)
( col newlat
( cons ( car lat) seen) ) ) ) )
¸else
( multirmber&co a
( cdr lat)
(lambda ( newlat seen)
( col ( cons ( car lat) newlat)
seen) ) ) ) ) ) )
Lambda the Utimate
This is not really difcult.
(defne multirmberT
(lambda ( test ? lat)
(cond
( ( null ? lat) (quote ( ) ) )
( ( test ? ( car lat) )
( multirmberT test ? ( cdr lat) ) )
(else ( cons ( car lat)
( multirmberT test?
( cdr lat) ) ) ) ) ) )
(shri mp sal ad sal ad and) .
It ' s not bad.
Now that looks really complicated!
137
Here is something simpler:
(defne afiend
(lbda ¦J y)
( null ? y)))
What is the vue of
( multirmber&co a lat col)
where
a is tuna
lat is (strawberries tuna and swrdfish)
and
col is afend
So let ' s try a friendlier example. What is the
vlue of ( multirmber&co Ü lat col)
where
a is tuna
lat is ¦ )
and
col is afend
And what is ( multirmber&co a lat col)
where
a is tuna
lat is (tuna)
and
col is afend
What are the other arguments that
multirmber&co uses for the natural
recursion?
What is the name of the third argument?
Do you know what col stands for?
138
Yes, it is simpler. It is a function that takes
two arguments and aks whether the second
one is the empty list. It ignores its frst
argnment.
This is not simple.
#t , because afend is immediately used in
the frst answer on two empty lists, and
afend makes sure that its second argument
is empty.
multirmber&co ak
( eqP ( car lat) (quote tuna) )
where
lat is (tuna) .
Then i t recurs on ( ) .
The frst one is clearly tuna. The third
argument is a new function.
col.
The name col is short for "collector. "
A collector is sometimes called a
"continuation. "
Chapter 8
Here is the new collector:
(defne newfiend
(lambda ( newlat seen)
( col newlat
( cons ( car lat) seen) ) ) )
where
( car lat) is tuna
and
col is afiend
Can you write this defnition diferently?
Can we also replace col with afiend in such
defnitions because col is to afiend what
( car lat) is to tuna
And now?
Which collector is this?
How does afiend difer from newfiend
And what does the old collector do with such
arguments?
What is the value of
( multirmber&co a lat afiend)
where a is tuna
and
lat is (and tuna)
Lambda the Utimate
Do you mean the new way where we put t una
into the defnition?
(defne newfiend
(lambda ( newlat seen)
( col newlat
( cons (quote tuna) seen) ) ) )
where
col is afiend.
Yes, we can:
(defne newfiend
(lambda ( newlat seen)
( afiend newlat
( cons (quote tuna) seen) ) ) )
multirember&co fnds out that ( null ? lat ) is
true, which means that it uses the collector
on two empty lists.
It is newfiend.
newfiend uses afiend on the empty list
and the value of
( cons (quote tuna) (quote ( ) ) ) .
I t answers #f, because its second argument
is (tuna) , which is not the empty list .
This time around multirmber&co recurs
with yet another friend.
(defne latestfiend
(lambda ( newlat seen)
( afiend ( cons (quote and) newlat)
seen) ) )
139
And what is the value of this recursive use of
multirmber&co
What does ( multirmber&co a lat f) do?
Final question: What is the value of
( multirmber&co (quote tuna) ls col)
where
ls is (strawberries tuna and swordfi sh)
and
col is
(defne lastfiend
(lambda ¸J y)
( length x) ) )
Yes!
#f, since ( afiend ls1 l2)
where
ls1 is (and)
and
ls2 is (tuna)
is #f.
It looks at every atom of the lat to see
whether it is eq? to a. Those atoms that are
not are collected in one list ls1 ; the others
for which the answer is true are collected in a
second list ls2. Finally, it determines the
value of (! ls1 l2) .
3, because ls contains three things that are
not tuna, and therefore lastfiend is used on
(strawberries and swordfi sh) and (tuna) .
It' s a strange meal , but we have seen foreign
foods before.
The Tenth Commandment
Build functions to collect more than one vlue at a time.
140 Chapter 8
Here is an old friend.
(defne multiinsertL
(lambda ( new old lat)
(cond
( ( null ? lat) (quote ( ) ) )
( ( eq? ( car lat) old)
( cons new
( cons old
( multiinsertL new old
( cdr lat ) ) ) ) )
(else ( cons ( car lat)
( multiinsertL new old
( cdr lat) ) ) ) ) ) )
Do you also remember multiinsertR
Now try multiinsertLR
Hint: multiinsertLR inserts new to the left
of oldL and to the right of oldR in lat if
oldL are oldR are diferent .
The function multiinsertLR&co i s to
multiinsertLR what multirmber&co is to
multirmber
Yes, and what kind of argument is it?
Lambda the Ultimate
No problem.
(defne multiinsertR
(lambda ( new old lat)
(cond
( ( null ? lat) (quote ( ) ) )
( ( eq? ( car lat) old)
( cons old
( cons new
( multiinsertR new old
( cdr lat ) ) ) ) )
(else ( cons ( car lat)
( multiinsertR new old
( cdr lat ) ) ) ) ) ) )
This i s a way of combining the two functions.
(defne multiinsertLR
(lambda ( new oldL oldR lat)
(cond
( ( null ? lat) ¸quote ( ) ) )
( ( eq? ( car lat) oldL)
( cons new
( cons oldL
( multiinsertLR new oldL oldR
( cdr lat ) ) ) ) )
( ( eq? ( car lat) oldR)
( cons oldR
( cons new
( multiinsertLR new oldL oldR
( cdr lat ) ) ) ) )
(else
( cons ( car lat)
( multiinsertLR new oldL oldR
( cdr lat ) ) ) ) ) ) )
Does this mean that multiinsertLR&co takes
one more argument than multiinsertLR?
It is a collector function.
141
When multiinsertLR&co is done, it will use
col on the new lat , on the number of lef
insertions, and the number of rght
insertions. Can you write an outline of
multiinsertLR&co
Why is col used on ¸quote ( ) ) 0 and 0 when
( null ? lat) is true?
So what is the value of
( multiinsertLR&co
¸quote cranberri es)
¸quote fi sh)
¸quote chi ps)
¸quote ¸ ) )
col)
Is it true that multiinsertLR&co will use the
new collector on three arguments when
( car lat) is equal to neither oldL nor oldR
142
Sure, it is j ust like multiinsertLR.
(defne multiinsertLR&co
(lambda ( new oldL oldR lat col)
(cond
( ( null ? lat)
( col ¸quote ( ) ) 0 0) )
( ( eq? ( car lat) oldL)
( multiinsertLR&co new oldL oldR
( cdr lat)
(lambda ( newlat L R)
. . . ) ) )
( ( eq? ( car lat) oldR)
( multiinsertLR&co new oldL oldR
( cdr lat)
(lambda ( newlat L R)
. . . )))
¸else
( multiinsertLR&co new oldL oldR
( cdr lat)
(lambda ( newlat L R)
. . . ) ) ) ) ) )
The empty lat contains neither oldL nor
oldR. And this means that 0 occurrences of
oldL and 0 occurrences of oldR are found and
that multiinsertLR will return () when lat is
empty.
It is the value of ( col (quote ( ) ) 0 0) , which
we cannot determine because we don' t know
what col is.
Yes, the frst is the lat that multiinsertLR
would have produced for ( cdr lat ) , oldL, and
oldR. The second and third are the number
of insertions that occurred to the left and
right of oldL and oldR, respectively.
Chapter 8
Is it true that multiinsertLR&co then uses
the function col on ( cons ( car lat) newlat)
because it copies the list unless an oldL or an
oldR appears?
Why are col' s second and third arguments
j ust L and R
Here is what we have so far. And we have
even thrown in an extra collector:
(defne multiinsertLR&co
(lambda ( new oldL oldR lat col)
(Lond
( ( null ? lat)
( col (quote ( ) ) 0 0) )
( ( eq? ( car lat) oldL)
( multiinsertLR&co new oldL oldR
( cdr lat)
(lambda ( newlat L R)
( col ( cons new
( cons oldL newlat) )
( add1 L) R) ) ) )
( ( eq? ( car lat) oldR)
( multiinsertLR&co new oldL oldR
( cdr lat)
(lambda ( newlat L R)
. . . ) ) )
(elÜe
( multiinsertLR&co new oldL oldR
( cdr lat)
(lambda ( newlat L R)
( col ( cons ( car lat) newlat)
L R) ) ) ) ) ) )
Can you fll i n the dots?
So can you fll in the dots?
Lambda the Ultimate
Yes, it is true, so we know what the new
collector for the last cae is:
(lambda ( newlat L R)
( col ( cons ( car lat) newlat) L R) ) .
If ( car lat) i s neither oldL nor oldR, we do
not need to insert any new elements. So, L
and R are the correct results for both
( cdr lat) and all of lat .
The incomplete collector is similar to the
extra collector. Instead of adding one to L, it
adds one to R, and instead of consing new
onto consing oldL onto newlat , it conses oldR
onto the result of consing new onto newlat .
Yes, the fnal collector is
(lambda ( newlat L R)
( col ( cons oldR ( cons new newlat) )
L ( add1 R) ) ) .
143
What is the value of
( multiinsertLR&co new oldL oldR lat col)
where
new is salty
oldL is fi sh
oldR is chi ps
and
lat is (chi ps and fi sh ÕÎ fi sh and chi ps)
Is this healthy?
Do you remember what *functions are?
Now write the function evens only* which
removes all odd numbers from a list of nested
lists. Here is even?
(defne even?
(lambda ( n)
¸ ¯ ¸ 7 ¸ ÷ n 2) 2) n) ) )
What i s the value of ( evens only* l)
where
l is ( (9 1 2 8) 3 10 ( (9 9
) 7 6) 2)
144
It is the value of ( col newlat 2 2)
where
newlat is (chi ps sal ty and sal ty fi sh
ÕÎ sal ty fi sh and chi ps sal ty) .
Looks like lots of salt. Perhaps dessert is
sweeter.
Yes, all *functions work on lists that are
either
 empty,
 an atom consed onto a list , or
 a list consed onto a list.
Now that we have practiced this way of
writing functions, evens only* is j ust an
exercise:
(defne evensonly*
(lambda (l )
(cond
( ( null ? l) (quote ( ) ) )
( ( atom? ( car l ) )
(cond
( ( even? ( car l ))
( cons ( car l)
( evensonly* ( cdr l))))
¸else ( evensonly* ( cdr l ) ) ) ) )
(else ( cons ( evensonly* ( car l ))
( evensonly* ( cdr l ) ) ) ) ) ) )
( ( 2 8) 10 ( ( ) 6) 2) .
Chapter 8
What is the sum of the odd numbers in l
where
l is ( (9 1 2 8) 3 10 ( (9 9
) 7 6) 2)
What is the product of the even numbers in l
where
l is ( (9 1 2 8) 3 10 ( (9 9
) 7 6) 2)
Can you write the function evensonly*&co
It builds a nested list of even numbers by
removing the odd ones from its argument
and simultaneously multiplies the even
numbers and sums up the odd numbers that
occur in its argument .
Here is an outline. Can you explain what
( evensonly*&co ( car l) . . . ) accomplishes?
(defne evensonly*&co
(lambda ( l col)
(cond
( ( null ? l)
( col (quote ( ) ) 1 0) )
( ( atom? ( car l ))
fcond
( ( even? ( car l ) )
( evens only*&co ( cdr l)
(lambda ( newl p s)
( col ( cons ( car l) newl)
( 7 ( car ) p) s) ) ) )
(else ( evensonly*&co ( cdr l)
(lambda ( newl p s)
( col newl
p ( + ( car l) s) ) ) ) ) ) )
(else ( evensonly*&co ( car l )
o . . ) ) ) ) )
What does the function evensonly*&co do
after visiting all the numbers in ( car l)
Lambda the Ultimate
9 + 1 + 3 + 9 + 9 + 7 ° 38.
2 ? 8 ? 10 ? 6 ? 2 ° 1920.
This is full of stars!
It visits every number in the car of l and
collects the list without odd numbers, the
product of the even numbers, and the sum of
the odd numbers.
It uses the collector, which we haven' t
defned yet .
145
And what does the collector do?
Does this mean the unknown collector looks
roughly like this:
(lambda ( al ap as )
( evensonly*&co ( cdr l)
. . . ) )
And when ( evensonly*&co ( cdr l) . . . ) is
done with its job, what happens then?
What does the collector for
( evensonly*&co ( cdr l) . . . )
do?
Does this all make sense now?
What is the value of
( evensonly*&co l thelastfend)
where
l is ( (9 1 2 8) 3 10 ( (9 9) 7 6) 2) and
thelastfend is defned as follows:
(defne thelastfend
(lambda ( newl product sum)
( cons sum
( cons product
newl ) ) ) )
146
It uses evens only*&co to visit the cdr of l
and to collect the list that is like ( cdr l ) ,
without the odd numbers of course, as well
a the product of the even numbers and the
sum of the odd numbers.
Yes.
The yettobedetermined collector is used,
j ust as before.
It conses together the results for the lists in
the car and the cdr and multiplies and adds
the respective products and sums. Then it
passes these values to the old collector:
(lambda ( al ap as)
( evensonly*&co ( cdr l)
(lambda ( dl dp ds )
( col ( cons al dl)
,
7 ap dp)
( + as ds ) ) ) ) ) .
Perfect .
(38 1920 (2 8) 10 ( ( ) 6) 2) .
Chapter 8
Whew! Is your brain twisted up now? Go eat a pretzel ; don' t forget the mustard.
Lambda the Utimate 147
Are you in the mood for cavi ar
What is ( looking a lat)
where a i s caviar
and
lat is (6 2 4 cavi ar 5 7 3)
( looking a lat)
where a is caviar
and
lat is (6 2 grits cavi ar 5 7 3)
Were you expecting something diferent?
Tue enough, but what is the frst number
in the lat?
And what is the sixth element of lat
And what is the seventh element?
So looking clearly can' t fnd cavi ar
Here is looking
(defne looking
(lambda ( a lat)
( keeplooking a (pick 1 lat) lat) ) )
Write keeplooking
( looking a lat)
where a is cavi ar
md
lat is (6 2 4 caviar 5 7 3)
. . . and Agan, and Agan, and Agan, . . .
Then we must go looking for it.
#t ,
cavi ar is obviously in lat .
#f.
Yes, cavi ar is still in lat .
6.
7.
3.
Tue enough,
because the third element is gri ts, which
does not even resemble cavi ar.
We did not expect you to know this.
#t ,
because ( keeplooking a 6 lat) has the same
answer as ( keeplooking a (pick 1 lat) lat) .
149
What is (pick 6 lat)
where
lat is (6 2 4 cavi ar 5 7 3)
So what do we do?
What is (pick 7 lat)
where
lat is (6 2 4 cavi ar 5 7 3)
So what is ( keeplooking a 3 lat)
where a is cavi ar
and
lat is (6 2 4 cavi ar 5 7 3)
Which is?
Write keeplooking
Can you guess what sor stands for?
What is unusual about keeplooking
We call this "unnatural" recursion.
150
7.
( keeplooking a 7 lat)
where a is cavi ar
and
lat is (6 2 4 cavi ar 5 7 3) .
3.
It is the same Ü
( keeplooking a 4 lat ) .
#t .
(defne keeplooking
(lambda ( a sor lat)
(cond
( ( number? sor)
( keeplooking a (pick sor lat) lat) )
(else ( eq? sor a) ) ) ) )
Symbol or number.
It does not recur on Ü part of lat.
It is truly unnatural .
Chapter 9
Does keeplooking appear to get closer to its
goal?
Does it always get closer to its goal?
That is correct. A list may be a tup.
What is ( looking a lat)
where a is cavi ar
and
lat is (7 1 2 caviar 5 6 3)
Yes, it is strange. What happens?
Fnctions like looking are called partial
functions. What do you think the functions
we have seen so far are called?
Can you defne a shorter function that does
not reach its goal for some of its arguments?
For how many of its arguments does eternity
reach its goal?
Is eterity partial?
What is ( shif J)
where
x is ((a b) c)
. . . and Agan, and Again, and Again, . . .
Yes, from all available evidence.
Sometimes the list may contain neither cavi ar
nor gri ts.
Yes, if we start looking in (7 2 4 7 5 6 3), we
will never stop looking.
This is strange!
We keep looking and looking and looking . . .
They are called total .
(defne eterity
(lambda ¸ J)
( eterity J) ) )
None, and this i s the most unnatural
recursion possible.
It is the most partial function.
(a (b c) ) .
151
What is ( shif x)
where
x is ( (a b) ¸L d) )
Defne shif
Describe what shif does.
Now look at this function:
(defne align
(lambda (por)
(cond
( ( atom? por) por)
( ( apair? (frst por) )
( align ( shif pora) ) )
(elÜe ( build (frst por)
( align (second por) ) ) ) ) ) )
What does i t have i n common with
keeplooking
Why are we not guaranteed that align makes
progress?
Which commandment does that violate?
152
¦
a ( b
,
L d) ) ) .
This i s trivial ; it' s not even recursive!
(defne shif
(lambda (pair)
( build (frst (frst pair) )
( build (second (frst pair))
( second pair) ) ) ) )
Here are our words:
"The function shif takes a pair whose frst
component is a pair and builds a pair by
shifting the second part of the frst
component into the second component. "
Both functions change their arguments for
their recursive uses but in neither cae is the
change guaranteed to get us closer to the
goal.
In the second cLÏdline shif creates an
argument for align that is not a part of the
original argument .
The Seventh Commandment .
Chapter 9
Is the new argument at least smaller than
the original one?
Why not?
And?
Can you write a function that counts the
number of atoms in align' s arguments?
Is align a partial function?
Is there something else that changes about
the arguments to align and its recursive uses?
In what way is the frst component simpler?
Doesn' t this mean that length* is the wrong
function for determining the length of the
argument? Can you fnd a better function?
How much more attention should we pay to
the frst component?
. . . and Again, and Again, and Again, . . .
It does not look that way.
The function shif only rearranges the pair it
gets.
Both the result and the argument of shif
have the same number of atoms.
No problem:
(defne length*
(lambda (pora)
(cond
( ( atom? pora) 1)
(else
( + ( length* (frst por) )
( length* (second por) ) ) ) ) ) )
We don' t know yet. There may be arguments
for which it keeps aligning things.
Yes, there is. The frst component of a pair
becomes simpler, though the second
component becomes more complicated.
It is only a part of the original par's frst
component .
A better function should pay more attention
to the frst component.
At least twice as much.
153
Do you mean something like weight*
(defne weight*
(lambda (por)
(cond
( ( atom? por) I)
(else
( + ( 7 ( weight* (frst por) ) 2)
( weight* ( second por) ) ) ) ) ) )
What i s ( weight * x)
where
x is ¸ ¸a b) c)
And what is ( weight* x)
where
x is ¸a (b c) )
Does this mean that the arguments get
simpler?
Is align a partial function?
Here is shuje which is like align but uses
revpair from chapter 7, instead of shif:
(defne shuje
(lambda (por)
(cond
( ( atom? por) por)
( ( apair? (frst por) )
( shuje ( revpair por) ) )
( else ( build (frst por)
( shuje ( second por) ) ) ) ) ) )
Does this mean that shuje i s total?
154
That looks right .
7.
5.
Yes, the weight *' s of align' s arguments
become successively smaller.
No, it yields a value for every argument .
The functions shuje and rvpair swap the
components of pairs when the frst
component is a pair.
We don' t know.
Chapter 9
Let 's try it . What is the value of ( shufe x)
where
x is (a (b L) )
( shufe x)
where
x is (a b)
Okay, let ' s try something interesting. What
is the value of ( shufe x)
where
x is ¸ ¸a b) ¸L d) )
And how are we going t o do that?
Doesn' t this mean that we need to know the
value of ( shufe ( rvpair por) )
where
( rvair por) is ¸ ¸a b) ¸L d) )
And?
Is this function total?
(defÏe C
(lambda ( n)
(coÏd
( ( one ? n) 1)
(else
(cond
( ( even? n) ( C (+ n 2) ) )
(else ( C ( add1 ( 7 3 n) ) ) ) ) ) ) ) )
. . . and Agan, and Again, and Again, . . .
¸a ( b L) ) .
¸a b) .
To determine this value, we need to fnd out
what ( shufe ( rvair por) ) is
where
por is ((a b) ¸L d) ) .
We are going t o determine the value of
( shufe por)
where por i s ¸ ¸L d) ¸a b) ) .
Yes, we do.
The function shufe is not total because it
now swaps the components of the pair again,
which means that we start all over.
It doesn' t yield a value for 0, but otherwise
nobody knows. Thank you, Lothar Collatz
( 19101990) .
155
What is the value of ¸ A 1 0)
¸ A 1 1)
¸ A 2 2)
Here is the defnition of A
(defne A
(lambda ( n m)
(cond
( ( zero ? n) ( addl m) )
( ( zer? m) ¸ A ( subl n) 1) )
(else ¸ A ( subl n)
¸ A n ( subl m) ) ) ) ) ) )
What does A have i n common with shufe
and looking
How about an example?
Does A always give an answer?
Then what is ¸ A 4 3)
What does that mean?
156
2.
3.
7.
Thank you, Wilhelm Ackermann
( 18531946) .
A' s arguments, like shufe' s and looking' s,
do not necessarily decrease for the recursion.
That ' s easy: ¸ A 1 2) needs the value of
¸ A 0 ¸ A 1 1) ) . And that means we need the
value of ¸ A 0 3) .
Yes, i t i s total .
For all practical purposes, there is no answer.
The page that you are reading now will have
decayed long before we could possibly have
calculated the value of ¸ A 4 3) .
But answer came there none
And this was scarcely odd, because
They'd eaten every one.
The Walrus and The Carpenter
Lewis Carroll
Chapter 9
Wouldn' t it be great if we could write a
function that tells us whether some function
returns with a value for every argument ?
Okay, let' s write it .
Then let' s make it simpler. For a warmup
exercise, let ' s focus on a function that checks
whether some function stops for just the
empty list , the simplest of all arguments.
Here is the beginning of this function:
(defne willstop?
(lambda U)
. . . ) )
Can you fll i n the dots?
Does willstop? return a value for all
arguments?
Is willstop? total then?
Then let' s make up some examples. Here is
the frst one. What is the value of
( willstop? f)
where
f is length
So?
. . . and Agan, and Agan, and Again, . . .
It sure would. Now that we have seen
functions that never return a value or return
a value so late that it is too late, we should
have some tool like this around.
It sounds complicated. A function can work
for many diferent arguments.
That would simplify it a lot .
What does it do?
That' s the easy part : we said that it either
returns #t or #f, depending on whether the
argument stops when applied to ( ) .
Yes, i t i s. It always returns #t or #f.
We know that ( length l) is 0
where l is ( ) .
Then the value of ( willstop? length) should
be #t .
157
Absolutely. How about another example?
What is the value of ( willstop? eterity)
Does this mean the value of
( willstop ? eterity) is #f
Do we need more examples?
Okay, here is a function that could be an
interesting argument for willstop?
(defne lasttr
(lambda ¸J)
(and ( willstop? lasttry)
( eterity J) ) ) )
What i s ( willstop? lasttry)
We need to test it on ( )
What is the value of
(and ( willstop? lasttry)
( eternity (quote ( ) ) ) )
There are only two possibilities. Let ' s say
( willstop? lasttry) is #f
So ( lasttry (quote ( ) ) ) stopped, right?
But didn' t willstop? predict j ust the
opposite?
158
( eterity (quote ( ) ) ) doesn' t return a value.
We just saw that.
Yes, it does.
Perhaps we should do one more example.
What does it do?
If we want the value of ( lasttr (quote ( ) ) ) ,
we must determine the value of
(and ( willstop? lasttr)
( eterity (quote ( ) ) ) ) .
That depends on the value of
( willstop? lasttr) .
Oky, then (and #f ( eterity (quote ( ) ) ) ) ,
i s #f, since (and #f . . . ) i s always #f.
Yes, it did.
Yes, it did. We said that the value of
( willstop? lasttr) was #f, which really
means that lasttry will not stop.
Chapter 9
So we must have been wrong about
¸ o:sep?asrçy
Fine. If ¸ o:seµ°as rçy is #t
what is the value of ¸ asrç (quote ( ) ) )
What i s the value of ¸ ee¬:/ç (quote ¸ ) ) )
But that means we were wrong again!
What do you think this means?
Is this unique?
Is there any way around this problem?
What is (defne . . . )
. . . and Agan, and Agan, and Again, . . .
That ' s correct . It must return #t , because
o:sep ?always gives an answer. We said it
was total .
Now we j ust need to determine the value of
(and #t ¸ ee¬:/ç (quote ( ) ) ) ) ,
which i s the same as the value of
¸ e/e¬:ç (quote ¸ ) ) ) .
It doesn' t have a value. We know that it
doesn' t stop.
True, since this time we said that
¸ o:s/eµ? as rçy was #t .
Here is our meaning:
"We took a really close look at the two
possible cases. If we can defne o:s/ep ?,
then
¸ o:sep ?as/ rçy
must yield either #t or #f. But it
cannotdue to the very defnition of what
o:seµ?is supposed to do. This must
mean that o:sep ?cannot be defned. "
Yes, it is. It makes o:sep ?the frst
function that we can describe precisely but
cannot defne in our language.
No. Thank you,
Alan M. Turing ( 19121954)
and
Kurt Godel ( 19061978) .
This i s an interesting question. We j ust saw
that (defne . . . ) doesn' t work for o:s/ep ?.
159
So what are recursive defnitions?
Is this the function length
(defne length
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
What i f we didn' t have (defne . . . )
anymore? Could we still defne length
What does this function do?
(lambda ( l )
(cLnd
( ( null ? l) 0)
(else ( add1 ( eterity ( cdr l ) ) ) ) ) )
What happens when we use i t on a
nonempty list?
What does it mean for this function that
looks like length
Suppose we could name this new function.
What would be a good name?
How would you write a function that
determines the length of lists that contain
one or fewer items?
160
Hold tight, take a deep breath, and plunge
forward when you' re ready.
It sure is.
Without (defne . . . ) nothing, and especially
not the body of length, could refer to length.
It determines the length of the emi,tY list
and nothing else.
No answer. If we give eterity an argument,
it gives no answer.
It j ust won' t give any answer for nonempty
lists.
lengtho
because the function can only determine
the length of the empty list .
Well , we could try the following.
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1 ( lengtho ( cdr l ) ) ) ) ) )
Chapter 9
Almost, but (defne . . . ) doesn' t work for
lengtho
And what' s a good name for this function?
Is this the function that would determine the
lenghts of lists that contain two or fewer
items?
(lambda (l )
(cond
( ( null ? l) 0)
(else
( add1
((lambda ( l)
(cond
( ( null ? l) 0)
(else
( add1
((lambda ( l)
(cond
( ( null? l) 0)
(else
( add1
( eterity
( cdr l ) ) ) ) ) )
( cdr l ) ) ) ) ) )
( cdr l ) ) ) ) ) )
Now, what do you think recursion is?
. . . and Again, and Again, and Again, . . .
So, replace length0 by its defnition.
(lambda ( l )
(cond
( ( null ? l) 0)
(else
( add1
( (lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1
( eterity ( cdr l ) ) ) ) ) )
( cdr l ) ) ) ) ) )
That ' s easy: length9.
Yes, this is length�2 . We j ust replace eterity
with the next version of length.
What do you mean?
161
Well , we have seen how to determine the
length of a list with no items, with no more
than one item, with no more than two items,
and so on. How could we get the function
length back?
How long are the lists that we can make?
But we can' t write an infnite function.
And we still have all these repetitions and
patterns in these functions.
What do these patterns look like?
Let ' s do it !
Do you mean this?
( ( lambda ( length)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
eternity)
162
If we could write an infnite function in the
style of lengtho , length9, length9, . . . , then
we could write length0, which would
determine the length of all lists that we can
make.
Well , a list is either empty, or it contains one
element , or two elements, or three, or four,
. . . , or 1001 , . . .
No, we can' t.
Yes, we do.
All these programs contain a function that
looks like length. Perhaps we should abstract
out this function: see The Ninth
Commandment .
We need a function that looks j ust like length
but starts with (lambda ( length) . . . ) .
Yes, that ' s okay. I t creates length0 .
Chapter 9
Rewrite length9 in the same style.
Do we have to use length to name the
argument?
How about length9
Close, but there are still repetitions.
Where should we start?
. . . and Agan, and Agan, and Again, . . .
( (lambda (/)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1 (/ ( cdr l ) ) ) ) ) ) )
( ( lambda ( g)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1 ( g ( cdr l ) ) ) ) ) ) )
eterity) )
No, we j ust used f and g. As long as we are
consistent , everything's oky.
( ( lambda ( length)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
( ( lambda ( length)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
( ( lambda ( length)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
eterity) ) )
Tue. Let 's get rid of them.
Name the function that takes length as an
argument and that returns a function that
looks like length.
163
What ' s a good name for this function?
Okay, do this to lengtho
Is this length9
( (lambda ( mklength)
( mklength
( mklength eterity) ) )
(lambda ( length)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) ) )
Can you write length9 i n this style?
What is recursion like?
164
How about mklength for "make length" ?
No problem.
( ( lambda ( mklength)
( mklength eterity) )
(lambda ( length)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) ) )
It sure i s. And this i s length9.
( ( lambda ( mklength)
( mklength
( mklength
( mklength eterity) ) ) )
(lambda ( length)
(lambda ( l )
(cond
( ( null? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) ) )
Sure. Here i t is.
( ( lambda ( mklength)
( mklength
( mklength
( mklength
( mklength eterity) ) ) ) )
(lambda ( length)
(lambda ( l )
(cond
( ( null? l ) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) ) )
It i s like an infnite tower of applications of
mklength to an arbitrary function.
Chapter 9
Do we really need an infnite tower?
Could we guess how many we need?
When do we fnd out that we didn' t guess a
large enough number?
What if we could create another application
of mklength to eterity at this point?
Well , since nobody cares what function we
pass to mklength we could pass it mklength
initially.
Then is this still lengtho
( ( lambda ( mklength)
( mklength mklength) )
(lambda ( length)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1
( length ( cdr l ) ) ) ) ) ) ) )
Why would we want to do that?
. . . and Agan, and Agan, and Again, . . .
Not really of course. Everytime we use length
we only need a fnite number, but we never
know how many.
Sure, but we may not guess a large enough
number.
When we apply the function eternity that is
pased to the innermost mklength.
That would only postpone the problem by
one, and besides, how could we do that ?
That ' s the right idea. And then we invoke
mklength on eterity and the result of this
on the cdr so that we get one more piece of
the tower.
Yes, we could even use mklength instead of
length.
( (lambda ( mklength)
( mklength mklength) )
(lambda ( mklength)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1
( mklength ( cdr l ) ) ) ) ) ) ) )
All names are equal , but some names are
more equal than others. 1
1 With apologies t o George Orwell ( 1903 1950) .
165
True: as long as we use the names
consistently, we are j ust fne.
Now that mklength is passed to mklength
can we use the argument to create an
additional recursive use?
What is the value of
( ( (lambda ( mklength)
( mklength mklength) )
(lambda ( mklength)
(lambda ( l )
l)
(cond
( ( null ? l) 0)
(else ( add1
( ( mklength eterity)
( cdr l ) ) ) ) ) ) ) )
where
l is ( appl es)
Could we do this more than once?
166
And mklength is a far more equal name than
length. If we use a name like mklength, it is
a constant reminder that the frst argument
to mklength is mklength.
Yes, when we apply mklength once, we get
length9
( (lambda ( mklength)
( mklength mklength) )
(lambda ( mklength)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1
( ( mklength eterity)
( cdr l ) ) ) ) ) ) ) )
This i s a good exercise. Work i t out with
paper and pencil.
Yes, j ust keep passing mklength to itself,
and we can do this Ü often as we need to!
Chapter 9
What would you call this function?
( (lambda ( mklength)
( mklength mklength) )
(lambda ( mklength)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1
( ( mklength mklength)
( cdr l ) ) ) ) ) ) ) )
Ho does i t work?
One problem is left: it no longer contains the
function that looks like length
((lambda ( mklength)
( mklength mklength) )
(lambda ( mklength)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( ad
.
d1
<
I
<
mklength mklength)
( cdr l ) ) ) ) ) ) ) )
Can you fx that?
Why?
. . . and Agan, and Again, and Again, . . .
It is length, of course.
It keeps adding recursive uses by passing
mklength to itself, j ust Ü it is about to
expire.
We could extract this new application of
mklength to itself and call it length.
Because it really makes the function length.
167
How about this?
( ( lambda ( mklength)
( mklength mklength) )
(lambda ( mklength)
( ( lambda ( length)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
( mklength mklength) ) ) )
Yes, this looks j ust fne.
Let ' s see whether it works. Okay.
What is the value of It should be 1.
( ( (lambda ( mklength)
( mklength mklength) )
(lambda ( mklength)
((lambda ( length)
(lambda ( l )
l)
where
(cond
( ( null ? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
( mklength mklength) ) ) )
l i s (appl es)
First , we need the value of
((lambda ( mklength)
( mklength mklength) )
(lambda ( mklength)
( (lambda ( length)
(lambda ( l )
That ' s true, because the value of this
expression is the function that we need to
apply to l where
168
(cond
( ( null ? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
( mklength mklength) ) ) )
l i s (appl es)
Chapter 9
So we really need the value of
((lambda ( mklength)
((lambda ( length)
(lambda ( l )
(cond
( ( null? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
( mklength mklength) ) )
(lambda ( mklength)
((lambda ( length)
(lambda (l)
(cond
( ( null ? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
( mklength mklength) ) ) )
But then we really need to know the value of
((lambda ( length)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
((lambda ( mklength)
((lambda ( length)
(lambda ( l)
(cond
( ( null ? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
( mklength mklength) ) )
(lambda ( mklength)
((lambda ( length)
(lambda (l)
(cond
( ( null? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
( mklength mklength) ) ) ) )
. . . and Again, and Again, and Again, . . .
Tue enough.
Yes, that ' s true, too. Where is the end of
this? Don' t we also need to know the value
of
( (lambda ( length)
(lambda ( l )
(cond
( ( null ? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
( ( lambda ( length)
(lambda ( l )
(cond
( ( null? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
( (lambda ( mklength)
((lambda ( length)
(lambda (l)
(cond
( ( null ? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
( mklength mklength) ) )
(lambda ( mklength)
( (lambda ( length)
(lambda ( l )
(cond
( ( null? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) )
( mklength mklength) ) ) ) ) )
169
Yes, there is no end to it . Why?
Is this strange?
But now that we have extracted
( mklength mklength)
from the function that makes length
it does not return a function anymore.
Trn the application of mklength to itself in
our last correct version of length into a
function:
( ( lambda ( mklength)
( mklength mklength) )
(lambda ( mklength)
(lambda ( l )
(cond
( ( null ? l) 0)
(else
(
add1
(
j'
(
m

k



le

ng
_
t
_
h

m

k

l

en

g

th

)
(
cdr l ) ) ) ) ) ) ) )
Here i s a diferent way. If f i s a function of
one argument , is (lambda ¸J) (f J) ) a
function of one argument?
If ( mklength mklength) returns a function
of one argument , does
(lambda ¸ J)
( ( mklength mklength) J) )
return a function of one argument?
170
Because we j ust keep applying mklength to
itself again and again and again . . .
It is because mklength used to return a
function when we applied it to an argument.
Indeed, it didn' t matter what we applied it
to.
No it doesn' t. So what do we do?
How?
Yes, it is.
Actually,
(lambda ¸J)
( ( mklength mklength) J) )
i s Ü function!
Chapter 9
Okay, let' s do this to the application of
mklength to itself.
Move out the new function so that we get
length back.
Is it oky to move out the function?
Can we extract the function in the box that
looks lik length and give it a name?
. . . and Agan, and Again, and Again, . . .
( ( lambda ( mklength)
( mklength mklength) )
(lambda ( mklength)
(lambda ( l )
(cond
( ( null ? l) 0)
(else
( add1
("(1 =ambd;a'(x )
( ( mklength mklength) x) )
( cdr l ) ) ) ) ) ) ) )
( ( lambda ( mklength)
( mklength mklength) )
(lambda ( mklength)
( (lambda ( length)
(lambda ( l )
(cond
( ( null ? l) 0)
(else
( add1 ( length ( cdr l ) ) ) ) ) ) )
(lambda ( x)
( ( mklength mklength) x) ) ) ) )
Yes, we j ust always did the opposite by
replacing a name with its value. Here we
extract a value and give it a name.
Yes, it does not depend on mklength at all !
171
Is this the right function?
( (lambda ( le)
((lambda ( mklength)
( mklength mklength) )
(lambda ( mklength)
( le (lambda ( x)
( ( mklength mklength) x) ) ) ) ) )
(lambda ( length)
(lambda ( l )
(cond
( ( null? l) 0)
(else ( add1 ( length ( cdr l ) ) ) ) ) ) ) )
Yes.
What did we actually get back? We extracted the original function mklength.
Let ' s separate the function that makes length That 's easy.
from the function that looks like length
Does this function have a name?
Does (defne . . . ) work again?
Do you now know why Y works?
172
(lambda ( le)
((lambda ( mklength)
( mklength mklength) )
(lambda ( mklength)
( le (lambda ( x)
( ( mklength mklength) x) ) ) ) ) )
Yes, i t i s called the applicativeorder Y
combinator.
(defne Y
(lambda ( le)
( ( lambda (/) (/
f
) )
(lambda (/)
( le (lambda ( x) ( (/ f
) x) ) ) ) ) ) )
Sure, now that we know what recursion is.
Read this chapter j ust one more time and
you will.
Chapter 9
What is ( Y Y)
Does your hat still ft?
. . . and Again, and Again, and Again, . . .
Who knows, but it works very hard.
Perhaps not after such a mind stretcher.
Stop the World/ Want to Get Of.
Leslie Bricusse and Anthony Newley
173
:€
�&�W
� J � t C10� �
An entry is a par of lists whose frst list is a
set. Also, the two lists must be of equal
length. Make up some examples for entries.
How can we build an entry from a set of
names and a list of values?
What is ( lookupin entr name entr)
where name is entree
and
entr is ( ( appeti zer entree beverage)
(food tastes good) )
What i f name i s dessert
How can we accomplish this?
How many arguments do you think this extra
function should take?
What Is the Vaue of All of This?
Here are our examples:
( (appeti zer entree beverage)
( pate boeuf vi n) )
and
( (appeti zer entree beverage)
( beer beer beer) )
and
( ( beverage dessert)
( (food i s) ( number one wi th us) ) ) .
(defne newentry build)
Ty to build our examples with this function.
tastes.
In this cae we would like to leave the
decision about what to do with the user of
lookupin entry.
lookupinentry takes an additional argument
that is invoked when name is not found in
the frst list of an entry.
We think it should take one, name. Why?
175
Here is our defnition of lookupinentr
(defne lookupinentr
(lambda ( name entr entrf)
( lookupinentrhelp name
(frst entr)
(second entr)
entrf) ) )
Finish the function lookupinentrhelp
(defne lookupinentrhelp
(lambda ( name names values entrf)
(cond
(
)
( )
(
) ) ) )
A table ¸also called an environment)i s a list
of entries. Here is one example: the empty
table, represented by ()
Make up some others.
Defne the function extendtable which takes
an entry and a table ¸possibly the empty
one) and creates a new table by putting the
new entry in front of the old table.
What is
( lookupintable name table tablef)
where
name is entree
table is ( ( ¸entree dessert)
¸spaghetti spumoni ) )
and
( ¸appetizer entree beverage)
(food tastes good) ) )
table/ i s ¸lambda ( name) . . . )
176
(defne lookupinentrhelp
(lambda ( name names values entrf)
(cond
( ( null? names) ( entr/ name) )
( ( eq? ( car names) name)
( car values) )
(else ( lookupinentryhelp name
( cdr names)
( cdr values)
entrf) ) ) ) )
Here i s another one:
¸ ¸ ¸appeti zer entree beverage)
¸ pate boeuf vi n) )
¸ ¸ beverage dessert)
¸ ¸food i s) ¸number one wi th us) ) ) ) .
¸defne extendtable cons)
It could be either spaghetti or tastes, but
lookupintable searches the list of entries in
order. So it is spaghetti .
Chapter 1 0
Write lookupintable
Hint: Don't forget to get some help.
Can you describe what the following function
represents:
(lambda ( name)
( lookupintable name
( cdr table}
tablef))
In the preface we mentioned that sans serif
typeface would be used to represent atoms.
To this point it ha not mattered.
Henceforth, you must notice whether or not
an atom is in sans serif.
Did you notice that "sans serif" wa not in
sans serif?
Have w chosen a good representation for
expressions?
What kind of functions?
Do you remember value from chapter 6?
What is the value of
( car (quote {a b c) ))
What Is the Vaue of All of This?
(defÎe lookupintable
(lambda (name table tablef)
[LoÎd
( ( null ? table) ( table! name) )
(elÜe ( lookupinentry name
( car table}
(lambda ( name)
( lookupintable name
( cdr table}
tablef) ) ) ) ) ) )
This function i s the action to take when the
name is not found in the frst entry.
Remember to be very conscious Ûb to whether
or not an atom i s i n sans serif.
We hope so. This is ¯sÛnb serif'
in sans serif.
Yes. They are all Sexpressions so they can
be data for functions.
For example, value.
Recal that value is the function that returns
the natural value of expressions.
We don't even know what (quote {Û b c) ) is.
177
What is the value of
¦ cons rpa
( cons rpb
( cons rpc
(quote ( ) ) ) ) )
where
repa is a
rpb is b
and
rpc is c
Great . And what is the value of
( cons rpcar
( cons ( cons rpquote
( cons
( cons repa
( cons rpb
¦ cons repc
(quote ( ) ) ) ) )
(quote ( ) ) ) )
(quote ( ) ) ) )
where
rpcar is car
repquote is quote
rpa is a
repb is b
and
rpc is c
What is the value of
( car (quote (a b c) ) )
What i s ( value e)
where
e is (car (quote (a b c)) )
What i s ¸ value e)
where
e is (quote (car (quote (a b c) ) ) )
178
It is the same a (a b L) 
It is a representation of the expression:
(car (quote (a b c) ) ) .
a.
a.
(car (quote (a b c) ) ) .
Chapter 10
What is ( value e)
where
e is (addl 6)
What is ( value e)
where e is 6
What is ( value e)
where
e is (quote nothi ng)
What is ( value e)
where
e is nothi ng
What is ( value e)
where
e is ( ( l ambda (nothi ng)
(cons nothi ng (quote ())))
(quote
(from nothi ng comes somethi ng) ) )
What i s ( value e)
where
e is ((l ambda (nothi ng)
(cond
(nothi ng (quote somethi ng))
(else (quote nothi ng) ) ) )
#t )
What is the type of Û
where
e is 6
What is the type of e
where
e is #f
What Is the Vaue of All of This?
7.
6, because numbers are constants.
nothi ng.
nothi ng has no value.
( (from nothi ng comes somethi ng) ) .
somethi ng.
*const.
*const.
179
What is { value e)
where
e is #f
What is the type of e
where e is cons
What is ( value e)
where e i s car
What is the type of e
where
e is {quote nothi ng)
What is the type of e
where
e is nothi ng
What is the type of e
where
e is (l ambda ¸A y) (cons A y))
What is the type of e
where
e is ((l ambda (nothi ng)
(cond
(nothi ng (quote somethi ng))
(else (quote nothi ng) ) ) )
#t )
What is the type of e
where
e is (cond
180
(nothi ng (quote somethi ng))
(else (quote nothi ng)))
#f.
*const.
{pri mi tive car) .
*quote.
*identifer.
*lambda.
*application.
*cond.
Chapte 10
How many types do you think there are?
How do you think we should represent types?
If actions are functions that do "the right
thing" when applied to the appropriate type
of expression, what should value do?
Do you remember atomtofnction from
chapter 8?
Below is a function that produces the correct
action (or function)for each possible
Sexpression:
(defne exrssiontoaction
(lambda ( e)
(cond
( ( atom? e) ( atomtoaction e) )
(else ( listtoaction e) ) ) ) )
Defne the function atomtoaction
1
1
Illformed Sexpressions such a (quote a b), () ,
(l ambda (#t) #t), (l ambda (5) 5), ( l ambda (car) car) ,
(l ambda a) , (cond (3 c) (else b) (6 a)), and (1 2) are not
considered here. They can be detected by an appropriate
function to which Sexpressions are submitted before they
are pased on to value.
What Is the Value of All of This?
We found six:
*const
*quote
*identifer
*lambda
*cond
and
*application.
We choose functions. We call these functions
"actions. "
You guessed it. It would have to fnd out the
type of expression it was passed and then use
the associated action.
We found. atomtofnction useful when we
rewrote value for numbered expresssions.
(defne atomtoaction
(lambda ( e)
(cond
( ( number? e) *const)
( ( eq? e #t ) *const)
( ( eq? e #f ) *const)
( ( eq? e (quote cons) ) *const)
( ( eq? e (quote car) ) *const)
( ( eq? e (quote cdr) ) *const)
( ( eq? e (quote nul l ?) ) *const)
( ( eq? e (quote eq?)) *const)
( ( eq? e (quote atom?)) *const)
( ( eq? e (quote zero?) ) *const)
( ( eq? e (quote add1) ) *const)
( ( eq? e (quote sub1) ) *const)
( ( eq? e (quote number?) ) *const)
(else *identifer))))
181
Now defne the help function listtoaction
Assuming that exrssiontoaction works,
we can use it to defne value and meaning
(defne value
(lambda ( e)
(meaning e (quote ( ) ) ) ) )
(defne meaning
(lambda ( e table)
( ( exressiontoaction e) e table) ) )
What i s (quote ()) i n the defnition of value
(defne listtoaction
(lambda ( e)
(cond
( ( atom? ( car e) )
(cond
( ( eq? ( car e) (quote quote) )
*quote)
( ( eq? ( car e) (quote l ambda})
*lambda)
( ( eq? ( car e) (quote cond} }
*cond}
(else *application) ) )
(else *application)) ))
It i s the empty table. The function value,
1
together with all the functions it uses, is
called an interpreter.
1
The function value approximates the function eVa1
available in Scheme (and Lisp).
Actions do speak louder than words.
How many arguments should actions take
according to the above?
182
Two, the expression e and a table.
Chapter 1 0
Here is the action for constants.
(defne *const
(lambda ( e table)
(Lond
(( number? e) e)
(( eq? e #t ) #t )
( ( eq? e #f ) #f )
(else ( build (quote pri mi tive) e) ) ) ) )
Is i t correct?
Here is the action for *quote
(defne *quote
(lambda ( e table)
( textof e)))
Defne the help function textof
Have we used the table yet?
Why do we need the table?
Given that the table contains the vlues of
identifers, write the action *identifer
Here is initialtable
(defne initialtable
(lambda ( name)
( car (quote ()))))
When i s i t used?
What is the vlue of (l ambda ¦A) A)
What Is the Vaue of All of This?
Yes, for numbers, it j ust returns the
expression, and this is all we have to do for
0, 1 , 2, . . .
For #t , it returns true.
For #f , it returns false.
And all other atoms of constant type
represent primitives.
(defne textof second)
No, but we will in a moment .
To remember the vlues of identifers.
(defne *identifer
(lambda ( e table)
( lookupintable e table initialtable) ) )
Let's hope never. Why?
We don' t know yet, but we know that it
must be the representation of a nonprimitive
function.
183
How are nonprimitive functions diferent
from primitives?
So when we want to use a nonprimitive we
need to remember its formal arguments and
its function body.
And what else do we need to remember?
And how do we represent this?
Here is the action *lambda
(defne *lambda
(lambda ( e table)
( build (quote nonpri mi ti ve)
( cons table ( cdr e) ) ) ) )
What i s ( meaning e table)
where
e is ( l ambda ¸x) (cons x y) )
and
table is (( (y z) ( (8)
9
) ) )
I t i s probably a good idea t o defne some
help functions for getting back the parts in
this three element list (i. e. , the table, the
formal arguments, and the body) . Write
tableof formals of and body of
Describe ( cond . . . ) in your own words.
184
We know what primitives do; nonprimitives
are defned by their arguments and their
function bodies.
At least. Fortunately this is j ust the cdr of a
l ambda expression.
We will also put the table in, j ust in case we
might need it later.
In a list , of course.
( nonpri mi ti ve
( ( ( (y z) ( (8) 9) ) ) ¸x) (cons x y) ) )
� � �
table formals body
(defne tableof frst)
(defne formalsof second)
(defne body of thir)
It is a special form that takes any number of
condlines. It considers each line in turn. If
the question part on the left is false, it looks
at the rest of the lines. Otherwise it proceeds
to answer the right part . If it sees an
elseline, it treats that condline as if its
question part were true.
Chapter 10
Here is the function evcon that does what we
j ust said in words:
(defne evcon
(lambda ( lines table)
(cond
( ( else? ( question of ( car lines) ) )
( meaning ( answer of ( car lines ) )
table) )
( ( meaning ( question of ( car lines ) )
table)
( meaning ( answerof ( car lines ) )
table) )
(else ( evcon ( cdr lines) table) ) ) ) )
Write else? and the help functions
questionof and answer of
Didn' t we violate The First Commandment?
Now use the function evcon to write the
*cond action.
Aren' t these help functions useful?
Do you understand *cond now?
How can you become familiar with it?
What Is the Value of All of This?
(defne else ?
(lambda ¸J)
(cond
( ( atom? J) ( eq? J (quote el se) ) )
(else #f ) ) ) )
(defne questionof frst)
¸defne answer of second)
Yes, we don' t ask ( null ? lines ) , so one of the
questions in every cond better be true.
¸defne *cond
(lambda ( e table)
( evcon ( condlinesof e) table) ) )
¸defne condlinesof cdr)
Yes, they make things quite a bit more
readable. But you already knew that.
Perhaps not .
The best way is to try an example. A good
one is:
( *cond e table)
where
e is (cond (coffee kl atsch) (el se party) )
and
table is (( (cofee) ( #t ) )
( ( kl atsch party) (5 (6) ) ) ) .
185
Have we seen how the table gets used?
But how do the identifers get into the table?
How is an application represented?
How does an application difer from a special
form, like (and . . . ) (or . . . ) or (cond . . . )
Before we can apply a function, do we have
to get the meaning of all of its arguments?
Write a function evlis that takes a list of
( representations of) arguments and a table,
and returns a list composed of the meaning
of each argument .
What else do we need before we can
determine the meaning of an application?
And what then?
Here is *application
(defne *application
(lambda ( e table)
( apply
( meaning (fnction of e) table)
( evlis ( arumentsof e) table) ) ) )
Is i t correct?
186
Yes, *lambda and *identifer use it .
In the only action we have not defned:
*application.
An application is a list of expressions whose
car position contains an expression whose
value is a function.
An application must always determine the
meaning of all its arguments.
Yes.
(defne evlis
(lambda ( ars table)
(cond
( ( null ? ars) (quote ( ) ) )
(else
( cons ( meaning ( car ars ) table)
( evlis ( cdr ars) table) ) ) ) ) )
We need to fnd out what its fnctionof
means.
Then we apply the meaning of the function
to the meaning of the arguments.
Of course. We j ust have to defne apply,
fnctionof, and arumentsof correctly.
Chapter 1 0
Write fnctionof and arumentsof
How many diferent kinds of functions are
there?
What are the two representations of
functions?
Write primitive ? and nonprimitive ?
Now we can write the function apply
What Is the Vaue of All of This?
(defne fnctionof car)
(defne arumentsof cdr)
Two: primitives and nonprimitives.
(pri mi tive primitivename) and
( non pri mi tive ( table formals body) )
The list ( table formals body) i s called a
closure record.
(defne primitive ?
(lambda ( l )
( eq? (frst l) (quote pri mi tive) ) ) )
(defne nonprimitive ?
(lambda ( l )
( eq? (frst l) (quote nonpri mi ti ve) ) ) )
Here i t is:
¸defne apply1
(lambda (fn vals )
(cond
( (primitive ? fn)
( applyprimitive
(second fn) vals) )
( ( nonprimitive ? fn)
( applyclosur
(second fn) vals) ) ) ) )
1 I f fn does not evaluate to either a primitive or a
nonprimitive a in the expression ( ( l ambda (x) (x 5) ) 3) ,
there i s no answer. The function apply approximates the
function agg1§ available in Scheme ( and Lisp) .
187
This is the defnition of applyprimitive
(defne applyprimitive
(lambda ( name vals )
(cond
(( eq? name 1 )
( cons (frst vals ) (second vals) ) )
( ( eq? name (quote car) )
( car (frst vals) ) )
( ( eq? name (quote cdr) )
( 2 (frst vals) ) )
( ( eq? name (quote nul l ?) )
( null ? (frst vals) ) )
( ( eq? name (quote eq?) )
( 3 (frst vals) 4 ) )
( ( eq? name (quote atom?) )
( 5 (frst vals) ) )
( ( eq? name (quote zero?))
( zer? (frst vals) ) )
( ( eq? name (quote add1) )
( add1 (frst vals) ) )
( ( eq? name (quote sub1) )
(sub1 (frst vals) ) )
( ( eq? name (quote number?) )
( number? (frst vals) ) ) ) ) )
Fill i n the blanks.
Is applyclosur the only function left ?
How could we fnd the result of (f a b)
where
f is ( l ambda (x y) (cons x y) )
a i s 1
and
b is (2)
Why can we do this?
188
1. ¸quote cons)
2. cdr1
3. eq?
4. (second vals)
5. :atom?
¸defne :atom?
(lambda ¸J)
¸cond
( ( atom? J) #t )
( ( null ? J) #f )
( ( eq? ( car J) ¸quote pri mi ti ve) )
#t )
( ( eq? ( car J) ¸quote nonpri mi ti ve) )
#t )
¸else #f ) ) ) )
1 The function apply·primitive could check for applications
of cdr to the empty list or sub1 to 0, etc.
Yes, and applyclosur must extend the table.
That ' s tricky. But we know what to do to
fnd the meaning of
(cons x y)
where
table is ( ( (x y)
(1 (2) ) ) ) .
Here, we don' t need applyclosur.
Chapter 1 0
Can you generalize the last two steps?
Have you followed all this?
This is a complicated function and it
deserves an example.
What will be the new arguments of meaning
What Is the Value of All of This?
Applying a nonprimitive functiona
closureto a list of values is the same as
fnding the meaning of the closure' s body
with its table extended by an entry of the
form
(formals values)
In this entry, formals is the formals of the
closure and values is the result of evlis .
If not , here is the defnition of apply closur.
(defne applyclosur
(lambda ( closur vals)
( meaning ( bodyof closure)
( extend table
( newentry
(formalsof closur)
vals )
( tableof closur) ) ) ) )
In the following,
closur is ¸ ¸ ¸ ¸ U V W)
( 1 2 3) )
( (x y z)
(4 5 6) ) )
( x y)
¸LÕHb z x) )
and
vals is ( (a b L) (d Ü f) ) .
The new e for meaning will be ¸LLHb z x) and
the new table for meaning will be
( ( (x y)
((a b L) (d Ü f) ) )
¸ ¸ U V W)
(1 2 3) )
( (x y z)
(4 5 6) ) ) .
189
What is the meaning of ( cons Z J)
where Z is 6
and
J is (a b L)
Let ' s fnd the meaning of all the arguments.
What is
( evlis ars table)
where
ars is ¸Z x)
and
table is ( ( (x y)
( (a b c) (d e f) ) )
¸ ¸ U v W)
( 1 2 3))
( (x y z)
(4 5 6) ) )
What i s the ( meaning e table)
where e is z
What is ( meaning e table)
where e is x
So, what is the result of evlis
What is ( meaning e table)
where e is LÕHb
190
The same Ü
( meaning e table)
where
e is ¸LÕHb z x)
and
table is ( ( (x y)
((a b L) (d e f) ) )
¸ ¸ U v W)
( 1 2 3))
( (x y z)
(4 5 6) ) ) .
I n order t o do this, we must fnd both
( meaning e table)
where
e is z
and
( meaning e table)
where
e is x.
6, by using *identifer.
¸a b L) ¿ by using *identifer.
(6 ¸a b L) ) ¿ because evlis returns a list of the
meanings.
( pri mi ti ve LÕHb) ¿ by using *const.
Chapter 10
We are now ready to ( apply fn vals)
where
fn is ( pri mi ti ve LÕHb)
and
vals is (6 (a b L) )
Which path should we take?
Which condline is chosen for
( applyprimitive name vals)
where
name is LÕHb
and
vals is (6 (a b L) )
Are we fnished now?
But what about (defne . . . )
Is (defne . . . ) really not needed?
Does that mean we can run the interpreter
on the interpreter if we do the
transformation with the Y combinator?
What makes value unusual?
Should willstop? see representations of
expressions?
Does it help?
else
What Is the Vaue of All of This?
The applyprimitive path.
The third:
( ( eq? name (quote LÕHb) )
( cons (frst vals) ( second vals ) ) ) .
Yes, we are exhausted.
It isn' t needed because recursion can be
obtained from the Y combinator.
Yes, but see The Seasoned Schemer.
Yes, but don' t bother.
It sees representations of expressions.
That may help a lot .
No, don' t botherwe can play the same
game again. We would be able to defne a
function like last try? that will show that we
cannot defne the new and improved
willstop?.
Yes, it ' s time for a banquet .
191
You' ve reached the intermission. What are your options? You could quickly run out and get the
rest of the show, The Seasoned Schemer, or you could read some of the books that we mention
below. All of these books are classics and some of them are quite old; nevertheless they have
stood the test of time and are all worthy of your notice. Some have nothing whatsoever to do
with mathematics or logic, some have to do with mathematics, but only by way of telling an
interesting story, and still others are j ust worth discovering. There should be no confusion: these
books are not here to prepare you to read the sequel , they are j ust for your entertainment. At
the end of The Seasoned Schemer you can fnd a set of references to Scheme and the reference
to Common Lisp. Do not feel obliged to j ump ahead to the next book. Take some time of and
read some of these books instead. Then, when you have relaxed a bit , perhaps removed some
of the calories that were foisted upon you, go ahead and dive into the sequel . Enjoy!
Abbott, Edwin A. Flatland. Dover Publications, Inc. , New York, 1952. ( Original publica
tion: Seeley and Co. , Ltd. , London, 1884. )
Carroll, Lewis. The Annotated Alice: Alice 's Adventurs in Wonderland and Through the
Looking Glass. Clarkson M. Potter, Inc. , New York, 1960. Introduction and notes by
Martin Gardner. Original publications under diferent titles: Alice 's Adventurs Under
Grund and Through the Looking Glass and Wat Alice Found Ther, Macmillan and
Company, London 1865 and 1872, respectively.
Halmos, Paul R. Naive Set Theory. Litton Educational Publishers, New York, 1960.
Hein, Piet. Groks. The MIT Press, Cambridge, Masachusetts, 1960.
Hofstadter, Douglas R. Godel, Escher, Bach: an Eteral Golden Bmid. Basic Books, Inc. ,
New York, 1979.
Nagel, Ernest and James R. Newman. Godel 's Prof. New York University Press, New
York, 1958.
P6lya, Gyorgy. How to Solve It. Doubleday and Co. , New York, 1957.
Smullyan, Raymond. To Mock a Mockingbir And Other Logic Puzzles Including an
Amazing Adventur in Combinatory Logic. Alfred A. Knopf, Inc. , New York, 1985.
Suppes, Patrick. Intrduction to Logic. Van Nostrand Co. , Princeton, New Jersey, 1957.
Intermission 193
ÏndCX
*application, 186 eq?c, 127
*cond, 185 eq?salad, 128
*const, 183 eq?tuna, 136
*identifer, 183 eqan?, 78
*lambda, 184 eqlist ?, 91 , 92, 94
*quote, 183 eqset ?, 1 14, 1 1 5
+, 60, 108 equal ?, 93
¯g 61 eternity, 151
7¿ 65 evcon, 185
+, 75 even?, 144
¡, 74 evensonly*, 144
<, 73 evensonly*fco, 145
¯ç 74 evlis , 186
>, 72, 73 expressiontoaction, 181
???, 74 extendtable, 1 76
1stsubex, 105, 106
2ndsubex, 106
frst, 1 1 9
frsts , 43, 44, 46
A, 156 formalsof, 184
afiend, 138 fllfn?, 122
apair?, 1 18
fn?, 120
add1 , 59 fnctionof, 187
addtup, 64
align, 152
initialtable, 183
allnums , 78
insertg, 132
answerof, 185
insertL, 5 1 , 132
apply, 187
insertL *, 86
applyclosure, 189
insertLf, 130
applyprimitive, 188
insertR, 4850, 132
arumentsof, 187
insertR *, 82
atom?, 10
insertRf, 130
atomtoaction, 181
intersect , 116
atomtofnction, 134
intersect?, 1 15
intersect all , 1 1 7
bodyof, 184
build, 1 19 keeplooking, 150
C, 155 lastfiend, 140
condlinesof, 185 lasttry, 158
cookies, 123 lat ?, 16, 19, 109
latestfiend , 139
difernce, 1 1 7
lefmost , 88
edd1 , 108
length, 76, 160
else ?, 185
length*, 1 53
Index 195
listto action, 182
looking, 149
lookupinentry, 1 76
lookupinentryhelp, 176
lookupintable, 177
makeset , 112
meaning, 182
member* , 87
member?, 22
multiinsertL, 56, 57, 141
multiinsertLR, 141
multiinsertLR&co, 142, 143
multiinsertR, 56, 141
multirmber, 53, 135
multirmber&co, 137
multirmbereq?, 136
multirmberf, 135
multirmberT, 137
multisubst, 57
new entry, 175
newfiend, 139
nonums , 77
nonprimitive ?, 187
numberd?, 99101
occur, 78
occur*, 85
oneto one ?, 122
one ?, 79
opertor, 106
pick, 76
primitive ?, 187
questionof, 185
rmber, 34, 37, 41, 94, 95
rmber*, 81
rmbereq?, 129
196
rmberf, 126, 128, 129
rempick, 77, 79
rvpair, 121
rvrl , 120, 121
second, 119
seconds , 122
seqL, 131
seqR, 131
seqrm, 133
seqS, 133
ser?, 108
set ?, 1 1 1
shif, 152
shufe, 154
sub1 , 59
subset ?, 1 13, 114
subst, 51, 133
subst *, 85
subst2, 52
table of, 184
textof, 183
thelastfiend, 146
thir, 1 19
tup+, 69, 71
union, 116
value, 102104, 106, 134, 135, 182
weight *, 154
willstop?, 157
JJJ¿ 117
Y, 172
yyy, 133
zub1 , 108
Index
The Ten Commandments
The First Commandment
The Fifth Commandment
When building a value with + ,always use
lat, ask (null? lat) and else. When recurring on a number, n, ask two questions about it: (zero? n) and else. When recurring on a list of Sexpressions, l, ask three question about it: (null? l), (atom? ( car l)), and else.
When recurring on a list of atoms, two questions about it:
0 for the value of the terminating line, for adding 0 does not change the value of an
addition. When building a value with x, always use
multiplying by 1 does not change the value of a multiplication. When building a value with consider line.
1 for the value of the terminating line, for
The Second Commandment
Use cons to build lists.
()
cons,
always
for the value of the terminating
The Third Commandment
When building a list, describe the first typical element, and then ral recursion.
cons
The Sixth Commandment
Simplify only after the function is correct.
it onto the natu
The Fourth Commandment
Always change at least one argument while recurring. When recurring on a list of atoms,
The Seventh Commandment
Recur on the nature:
• •
subparts
that are of the same
(cdrlat). When recurring on a num ber, n, use (sub1 n). And when recurring on a list of Sexpressions, l, use (carl) and (cdr l) if neither (null? l) nor (atom? (carl)) are
use true. It must be changed to be closer to termina tion. The changing argument must be tested in the termination condition: when using and when using
lat,
On the sublists of a list. On the subexpressions of an arithmetic
expression.
The Eighth Commandment
Use help functions to abstract from represen tations.
cdr,
test termination with
null? The Ninth Commandment
Abstract common patterns with a new func tion.
zero?.
sub1,
test termination with
The Tenth Commandment
Build functions to collect more than one value at a time.
The Five Rules
The Law of Car
The primitive empty lists.
car
is defined only for non
The Law of Cdr
The primitive
empty lists. The
cdr is defined only for non cdrof any nonempty list
is always another list.
The Law of Cons
The primitive
cons
takes two arguments.
The second argument to The result is a list.
cons must be a list.
The Law of Null?
The primitive
null?
is defined only for lists.
The Law of Eq?
The primitive eq'l takes two arguments.
Each must be a nonnumeric atom.
The Little Schemer
Fourth Edition
Daniel P. Friedman
Indiana Uni11ersity Bloomington, Indiana
Matthias Felleisen
Rice Uni11ersity Houston, Texas
Drawings by Duane Bibby Foreword by Gerald J. Sussman
The MIT Press Cambridge, Massachusetts London, England
III. recording. ISBN 0262560992 (pbk: alk.S34F75 005. Title. of: The little LISPer. Matthias. Little LISPer. No part of this book may be reproduced in any form by any electronic or mechanical means (including photocopying. Felleisen. @1989. 1st MIT Press ed. © 1996 Massachusetts Institute of Technology All rights reserved. First MIT Press Edition. Friedman. paper) 1. Rev.13'3dc20 9539853 CIP . Daniel P. em. This book was set by the authors and was printed and bound in the United States of America. Includes index. . Daniel P. drawings by Duane Bibby.4 ed. foreword by Gerald J. or information storage and retrieval) without permission in writing from the publisher. © 1986.73. Friedman and Matthias Felleisen. ed. 3rd ed. The little schemer / Daniel P. 1987. Sussman. II. 1996 QA76. LISP (Computer program language) I. p. 1974 by Scientific Research Associates. Scheme (Computer program language) 2.Original edition published as The Little LISPer . Library of Congress CataloginginPublication Data Friedman.
Helga.To Mary. and our children .
.
Do It. Numbers Games) 58) ((5. . and Again.( (Contents) (Foreword (Preface ix) xi) ((1. What Is the Value of All of T his?) 174) (Intermission 192) (Index 194)) .. Cons the Magnificent) 32) ((4..) 148) ((10.. and Again. Lambda the Ultimate) 124) ((9. Toys) 2) ((2. Friends and Relations) 110) ((8..) 14) ((3. Do It Again. and Again. *Oh My Gawd*: It's Full of Stars) 80) ((6. ... and Again . and Again. Shadows) 96) ((7.
.
and mixing chemicals. Lisp provides the glue for using a vast library of canned parts. One must learn to ritualize the process of developing sensitive material so that one gets consistent results over many years of work. naming. In engineering. much of the drill and practice that is necessary to learn the skills of constructing recursive processes and manipulating recursive datastructures. we must learn to do analysis to support our efforts in synthesis. For the student of Lisp programming. as in other creative arts. In support of this skill we had to learn the use of exposure meters to measure light intensities and the use of exposure time and development time to control the black level and the contrast in the image. The Little L ISPer can perform the same service that Hanon's finger exercises or Czerny's piano studies perform for the student of piano. programming requires a choice of medium. Some photographers choose to use blackandwhite 8x10 plates while others choose 35mm slides. it provides mechanisms for formalizing. This is in turn supported by even lower level skills such as loading film . Gerald J . In addition . procedures are firstclass data. with considerable wit . Most of the students (including me) came into that course hoping to learn how to be creativeto take pictures like the ones I admired by artists such as Edward Weston. developing and printing. On the first day the teacher patiently explained the long list of technical skills that he was going to teach us during the term. It has developed into a uniquely powerful and flexible family of software development tools. Lisp was initially conceived as a theoretical vehicle for recursion theory and for symbolic algebra. Each has its advantages and disadvantages. and stored in data structures. In 1967 I took an introductory course in photography. The Little LISPer is a unique approach to developing the skills underlying creative program ming in Lisp. We reprint it here with the permission of the author. Sussman Cambridge. produced by members of the user community. As with other languages. to be passed as arguments. One cannot build a beautiful and functional bridge without a knowledge of steel and dirt and considerable mathematical technique for using this knowledge to compute the properties of structures. Similarly.Foreword This foreword appeared in the second and third editions of The Little L ISPer. This flexibility is valuable. But what about creative composition? In order to be creative one must first gain control of the medium. providing wraparound support for the rapidprototyping of software systems. A key was Ansel Adams' "Zone System" for previsualizing the print values (blackness in the final print) in a photograph and how they derive from the light intensities in the scene. Like photography. In Lisp. The first laboratory session was devoted to finding out that developer feels slippery and that fixer smells awful. Lisp programs can easily manipulate the representations of Lisp programsa feature that has encouraged the development of a vast structure of program synthesis and analysis tools. such as crossreferencers. and saving the idiomsthe common patterns of usage that are essential to engineering design . Massachusetts Foreword ix . It painlessly packages. one cannot build a beautiful computer system without a deep understanding of how to "previsualize" the process generated by the procedures one writes. One can not even begin to think about organizing a great photograph without having the skills to make it happen . but most importantly. returned as values. Lisp is the medium of choice for people who enjoy free style and flexibility.
Preface
To celebrate the twentieth anniversary of Scheme we revised The Little LISPer a third time, gave it the more accurate title The Little Schemer, and wrote a sequel: The Seasoned Schemer. Programs accept data and produce data. Designing a program requires a thorough understand ing of data; a good program reflects the shape of the data it deals with. Most collections of data, and hence most programs, are recursive. Recursion is the act of defining an object or solving a problem in terms of itself. The goal of this book is to teach the reader to think recursively. Our first task is to decide which language to use to communicate this concept . There are three obvious choices: a natural language, such as English; formal mathematics; or a programming language. Natural languages are ambiguous, imprecise, and sometimes awkwardly verbose. These are all virtues for general communication, but something of a drawback for communicating concisely as precise a concept as recursion. The language of mathematics is the opposite of natural language: it can express powerful formal ideas with only a few symbols. Unfortunately, the language of mathematics is often cryptic and barely accessible without special training. The marriage of technology and mathematics presents us with a third , almost ideal choice: a programming language. We believe that programming languages are the best way to convey the concept of recursion. They share with mathematics the ability to give a formal meaning to a set of symbols. But unlike mathematics, programming languages can be directly experiencedyou can take the programs in this book, observe their behavior, modify them , and experience the effect of these modifications. Perhaps the best programming language for teaching recursion is Scheme. Scheme is inherently symbolicthe programmer does not have to think about the relationship between the symbols of his own language and the representations in the computer. Recursion is Scheme's nat ural computational mechanism; the primary programming activity is the creation of (potentially) recursive definitions. Scheme implementations are predominantly interactivethe programmer can immediately participate in and observe the behavior of his programs. And, perhaps most importantly for our lessons at the end of this book, there is a direct correspondence between the structure of Scheme programs and the data those programs manipulate. Although Scheme can be described quite formally, understanding Scheme does not require a particularly mathematical inclination. In fact , The Little Schemer is based on lecture notes from a twoweek "quickie" introduction to Scheme for students with no previous programming experience and an admitted dislike for anything mathematical . Many of these students were preparing for careers in public affairs. It is our belief that writing programs recursively in Scheme is essentially simple pattern recognition. Since our only concern is recursive programming, our treatment is limited to the whys and wherefores of just a few Scheme features: car, cdr, cons, eq? , null?, zero? , addl, subl, number?, and, or, quote, lambda, define, and cond. Indeed, our language is an idealized Scheme. The Little Schemer and The Seasoned Schemer will not introduce you to the practical world of programming, but a mastery of the concepts in these books provides a start toward understanding the nature of computation.
Preface
xi
What You Need to Know to Read This Book The reader must be comfortable reading English, recognizing numbers, and counting. Acknowledgments We are indebted to many people for their contributions and assistance throughout the devel opment of the second and third editions of this book. We thank Bruce Duba, Kent Dybvig, Chris Haynes, Eugene Kohlbecker, Richard Salter, George Springer, Mitch Wand, and David S . Wise for countless discussions that influenced our thinking while conceiving this book. Ghassan Abbas, Charles Baker, David Boyer, Mike Dunn, Terry Falkenberg, Rob Friedman, John Gateley, Mayer Goldberg, Iqbal Khan , Julia Lawall, Jon Mendelsohn, John Nienart , Jeffrey D. Perotti, Ed Robertson , Anne Shpuntoff, Erich Smythe, Guy Steele, Todd Stein, and Larry Weisselberg provided many important comments on the drafts of the book. We especially want to thank Bob Filman for being such a thorough and uncompromising critic through several readings. Finally we wish to acknowledge Nancy Garrett, Peg Fletcher, and Bob Filman for contributing to the design and 'IEXery. The fourth and latest edition greatly benefited from Dorai Sitaram 's incredibly clever Scheme typesetting program SLl\TE]X. Kent Dybvig's Chez Scheme made programming in Scheme a most pleasant experience. We gratefully acknowledge criticisms and suggestions from Shelaswau Bushnell, Richard Cobbe, David Combs, Peter Drake, Kent Dybvig, Rob Friedman, Steve Ganz, Chris Haynes, Erik Hilsdale, Eugene Kohlbecker, Shriram Krishnamurthi, Julia Lawall, Suzanne Menzel Collin McCurdy, John Nienart , Jon Rossie, Jonathan Sobel, George Springer, Guy Steele, John David Stone, Vikram Subramaniam , Mitch Wand, and Melissa WingardPhillips. Guidelines for the Reader Do not rush through this book. Read carefully; valuable hints are scattered throughout the text. Do not read the book in fewer than three sittings. Read systematically. If you do not fully understand one chapter, you will understand the next one even less. The questions are ordered by increasing difficulty; it will be hard to answer later ones if you cannot solve the earlier ones. The book is a dialogue between you and us about interesting examples of Scheme programs. If you can , try the examples while you read. Schemes are readily available. While there are minor syntactic variations between different implementations of Scheme (primarily the spelling of particular names and the domain of specific functions) , Scheme is basically the same throughout the world. To work with Scheme, you will need to define at om?, subl, and addl. which we introduced in The Little Schemer:
(define at om? (lambda
(x)
(and (not (pair?
x))
(not (null?
x)))))
To find out whether your Scheme has the correct definition of at om?, try (atom? (quote ())) and make sure it returns #f. In fact , the material is also suited for modern Lisps such as Common Lisp. To work with Lisp, you will also have to add the function atom?:
(defun atom? (not (listp
(x) x)))
xii
Preface
Moreover, you may need to modify the programs slightly. Typically, the material requires only a few changes. Suggestions about how to try the programs in the book are provided in the framenotes. Framenotes preceded by "S:" concern Scheme, those by "L:" concern Common Lisp. In chapter 4 we develop basic arithmetic from three operators: add1 , sub1 , and zero ?. Since Scheme does not provide add1 and sub1 , you must define them using the builtin primitives for addition and subtraction. Therefore, to avoid a circularity, our basic arithmetic addition and subtraction must be written using different symbols: + and  , respectively. We do not give any formal definitions in this book. We believe that you can form your own definitions and will thus remember them and understand them better than if we had written each one for you. But be sure you know and understand the Laws and Commandments thoroughly before passing them by. The key to learning Scheme is "pattern recognition ." The Commandments point out the patterns that you will have already seen . Early in the book, some concepts are narrowed for simplicity; later, they are expanded and qualified. You should also know that , while everything in the book is Scheme, Scheme itself is more general and incorporates more than we could intelligibly cover in an introductory text . After you have mastered this book, you can read and understand more advanced and comprehensive books on Scheme. We use a few notational conventions throughout the text , primarily changes in typeface for different classes of symbols. Variables and the names of primitive operations are in italic. Basic data, including numbers and representations of truth and falsehood, is set in sans serif. Keywords, i.e. , define, lambda, cond, else, and, or, and quote, are in boldface. When you try the programs, you may ignore the typefaces but not the related framenotes. To highlight this role of typefaces, the programs in framenotes are set in a typewriter face. The typeface distinctions can be safely ignored until chapter 10, where we treat programs as data. Finally, Webster defines "punctuation" as the act of punctuating; specifically, the act , practice, or system of using standardized marks in writing and printing to separate sentences or sentence elements or to make the meaning clearer. We have taken this definition literally and have abandoned some familiar uses of punctuation in order to make the meaning clearer. Specifically, we have dropped the use of punctuation in the lefthand column whenever the item that precedes such punctuation is a term in our programming language. Food appears in many of our examples for two reasons. First , food is easier to visualize than abstract symbols. (This is not a good book to read while dieting. ) We hope the choice of food will help you understand the examples and concepts we use. Second, we want to provide you with a little distraction. We know how frustrating the subject matter can be, and a little distraction will help you keep your sanity. You are now ready to start . Good luck! We hope you will enjoy the challenges waiting for you on the following pages. Bon appetit ! Daniel P. Friedman Matthias Felleisen
Preface
xiii
.
The Little Schemer .
.
which is a letter. Is it true that this is a list? (atom )1 Yes. 1 L. because u is a string of one character. Is it true that this is an atom? tu rkey Yes. 1 L. S: (quote (atom) ) or ' ( atom) Is it true that this is a list? (atom tu rkey or) Yes. because it is a collection of atoms enclosed by parentheses.Is it true that this is an atom? atom1 Yes. because 1492 is a string of digits. because atom is a string of characters beginning with the letter a . because •abc$ is a string of characters beginning with a letter or special character other than a left " ( " or right " ) " parenthesis. S: (quote atom) or 'atom "L:" and "S:" are described in the preface. because (atom) is an atom enclosed by parentheses. Is it true that this is an atom? 1492 Yes. Toys 3 . Is it true that this is an atom? •abc$ Yes. Is it true that this is an atom? u Yes. because tu rkey is a string of characters beginning with a letter.
because it is a list . Is it true that this is a list? ( ( ( how) are) ( (you) (doing so) ) far) Yes . because i t i s a collection of Sexpressions enclosed by parentheses. you . and the second one is an atom. ( (you ) (doing so) ) . How many Sexpressions are in the list (how are you doing so far) and what are they? Six. so. and far. because these are actually two Sexpressions not enclosed by parentheses. Is it true that this is a list? (how are you doing so far) Yes . because all atoms are Sexpressions. and far. Is it true that this is an Sexpression? xyz Yes. how. How many Sexpressions are in the list ( ( (how) are) ( (you ) (doing so) ) far) and what are they? Three. ( ( how) are) . Is it true that this is an Sexpression? (x y z ) Yes. Is it true that this is a list? ( (atom tu rkey) or) Yes. Is it true that this is an Sexpression? ((x y) z ) Yes. 4 Chapter 1 . because all lists are Sexpressions. because i t i s a collection of Sexpressions enclosed by parentheses. are. doing. The first one is a list containing two atoms. because the two Sexpressions are now enclosed by parentheses.Is it true that this is a list? (atom tu rkey) or No.
No answer.Is it true that this is a list? () Yes. No. This special Sexpression is called the null (or empty) list . of l car of the empty 1 L: nil The Law of C ar The primitive car is defined only for nonempty lists. because it is a collection of Sexpressions enclosed by parentheses. You cannot ask for the No answer. Yes. because (a b c) is the first Sexpression of this nonempty list . car of an atom . because it contains zero Sexpressions enclosed by parentheses. 1 You cannot as k for the list . because a is the first atom of this list . because () is just a list . Is it true that this is an atom? () Is it true that this is a list? (() () () ( ) ) What i s the car of l where l is the argument (a b c) What is the car of l where l is ((a b c) x y z) What is the c a r of l where l is hotdog What is the where l is () car (a b c). Toys 5 . a.
because (b c) is the list l without ( car l). " ( ( hotdogs)) is the first Sexpression of l . What is ( cdr l) where l is ( (x) t r) (t r) ." (b c) . What i s the cdr of l where l is (a b c) Note: "cdr" is pronounced "coulder. What is the cdr of l where l is (hamburger) () . What is the cdr of l where l is ((a b c) x y z) (x y z) ." What is ( cdr a) where a is hotdogs No answer. You cannot ask for the cdr of an atom. because ( cdr l) is just another way to ask for "the cdr of the list l. 6 Chapter 1 . What is ( car l) where l is ( ( ( hotdogs) ) (and) (pickle) relish) ( ( hotdogs) ) ." What is ( car ( car l)) where l is ( ( ( hotdogs)) (and ) ) (hotdogs) .What is the car of l where l is ( ( ( hotdogs)) (and) (pickle) relish) ( ( hotdogs) ) . because ( car l) is another way to ask for "the car of the list l. read as: "The list of the list of hotdogs.
" Toys 7 . 1 L: nil The Law of Cdr The primitive cdr is defined only for nonempty lists. since ( car l) is an atom. N o answer.What is ( cdr l) where l is () No answer. What does car take as an argument? What does cdr take as an argument? What is the cons of the atom a and the list l where a is peanut and l is ( butter and jelly) This can also be written "( cons a l)" . It takes any nonempty list . The cdr of any non empty list is always another list. 1 You cannot ask for the cdr of the null list . and cdr does not take an atom as an argument. because ((x y) ((c))) is ( cdr l). and (x y) is the car of ( cdr l ) . (((c))) . ( pea nut butter and jel ly) . What is ( car ( cdr l)) where l is ((b) (x y) ((c))) What is ( cdr ( cdr l)) where l is ((b) (x y) ((c))) What is ( cdr ( car l)) where l is (a (b (c)) d) (x y) . see The Law of Cdr. and (((c))) is the cdr of ( cdr l ) . It takes any nonempty list . because cons adds an atom to the front of a list . Read: "cons the atom a onto the list l. because ((x y) ((c))) is ( cdr l ) .
because cons adds any Sexpression to the front of a list. What is ( cons s l) where s is ((a b c)) and l is b No answer. 1 since the second argument l must b e a list .What is the cons of s and l where s is ( banana and) and l is (peanut butter and jelly) ( (ba nana and) peanut butter and jelly) . 1 In practice. What is ( cons where s is a and l is ( ) s l) (a) . What is ( cons s l) where s is (a b (c)) and l is () ((a b ( c))) . What is ( cons where s is a and l is b s l) No answer. Why? 8 Chapter 1 . and (car (cona a /3)) =a (cdr (cona a /3)} = /3. (cona a /3) works for all values a and /3. What does cons take as its arguments? cons takes two arguments: the first one is any Sexpression. the second one is any list . because () is a list . What is ( cons s l) where s is ( (help) this) and l is (is very ( ( hard) to learn) ) ( ( (help) this) is very ((hard) to learn ) ) .
The second argument to cons must be a list. Why? Is i t true that the list l i s the null list where l is ( ) Yes. because it is the list composed of zero Sexpressions. because (quote ( ) ) 1 is a notation for the null list . The result is a list. This question can also be written: ( null? l). because l is a nonempty list .The Law of Cons The primitive cons takes two arguments. Is ( null? l) true or false where l is (a b c) False. 1 L : null 1 L: Also 0 and •(). Why? What i s ( cons s ( CJJ. S: Also •().r l ) ) where s is a and l is ((b) c d ) (a c d ) . What is ( cons s ( car l)) where s is a and l is ((b) c d ) ( a b) . Toys 9 . What is ( null?1 (quote () )) True.
since s is a list. 1 In practice. except the empty list. The Law of Null? The primitive null ? is de fined only for lists. because ( atom ? s ) is just another way to ask "Is s is an atom?" 1 L: (defun atom? ( x ) (not (listp x ) ) ) S: (def ine atom? (lambda (x) (and (not (pair? x)) (not (null? x) ) ) ) ) Is ( atom ? s ) true or false where s is (Harry had a heap of apples) False. because Harry is a string of characters beginning with a letter. How many arguments does atom? take and what are they? It takes one argument. 10 Chapter 1 . Is ( atom ?1 s ) true or false where s is Harry True. (null? a) is false for everything. Is it true or false that where s is Harry s is an atom True.Is ( null ? a) true or false where a is spaghetti No answer/ because you cannot ask null? of an atom. The argument can be any Sexpression.
which i s an atom . False. since a1 and a2 are different atoms.Is ( atom ? ( car l)) true or false where l is (Harry had a hea p of a pples) Is ( atom ? ( cdr l)) true or false where l is (Harry had a heap of apples) Is ( atom ? ( cdr l)) true or false where l is (Harry) Is ( atom ? ( car ( cdr l))) true or false where l is (swi ng low sweet cherry oat) Is ( atom ? ( car ( cdr l))) true or false where l is (swing (low sweet) cherry oat) True or false: a1 and a2 are the same atom where a1 is Harry and a2 is Harry Is ( eq?1 a1 a2 ) true or false where a1 is Harry and a2 is Harry True. which is a list . True. False. True. and ( car ( cdr l)) i s low. "Are a1 and a2 the same nonnumeric atom?" 1 L: eq Is ( eq? a1 a2) true or false where a1 is margarine and a2 is butter False. because a1 is the atom Harry and a2 is the atom Harry. and ( car ( cdr l)) is (low sweet) . since ( cdr l) is (( low sweet) cherry oat ) . because ( cdr l) is (low sweet cherry oat ) . and Harry is an atom. False. because the list ( ) is not an atom . Toys 11 . True. because ( eq ? a1 a2 ) is just another way to ask. because ( car l) is Harry.
How many arguments does eq ? take and what are they? It takes two arguments. 12 Chapter 1 . Both of them must be nonnumeric atoms.1 6 and 7 are numbers. some numbers may be arguments of eq?. eq? if they are the same list. 1 ( ) and (strawberry) are lists. and the argument a is also the atom Mary. because ( car l) is the atom Mary. Is ( eq ? ( cdr l) a ) true or false where l is (sou red milk) and a is m i l k No answer. Is ( eq ? ( car l) a ) true or false where l is (Mary had a little lamb chop) and a is Mary True. The Law of Eq? The primitive eq? takes two ar guments. 1 In practice. lists m83' be arguments of eq?. 1 In practice. Each must be a non numeric atom. Two lists are Is ( eq ? n1 n2 ) true or false where n1 is 6 and n2 is 7 No answer. See The Laws of Eq? and Cdr. Is ( eq ? l1 l2 ) true or false where l1 is () and l2 is (strawberry) No answer.
==>Now go make yourself a peanut butter and jelly sandwich.Is ( eq? ( car l) ( car ( cdr l))) true or false where l is (beans beans we need jelly beans) True. ¢= This space reserved for JELLY STAINS! 13 . because it compares the first and second atoms in the list .
�))� �m��m �� �t.D��� ��m ��� .
True! Every lat is a list of atoms! Write the function lat ? using some. because each Sexpression in l is an atom . Good luck. and Again . but not necessarily all. . and Again. True or false: ( lat ? l) where l is ( (Jack) Sprat cou ld eat no chicken fat) False. True or false: ( lat ? l) where l is () True. of the following functions: car cdr cons null? atom ? and eq ? You were not expected to be able to do this yet . because it does not contain a list . True or false: a lat is a list of atoms. . True or false: ( lat? l) where l is (Jack (Sprat could) eat no chicken fat) False.True or false: ( lat ? l) where l is (Jack Sprat could eat no chicken fat) True. Do It Again. Go on to the next question . 15 . since ( car l) is a list . since one of the Sexpressions in l is a list. because you are still missing some ingredients. Are you rested? Do It.
What is the meaning of the cond line ( (null? l) #t ) where l is (bacon and eggs)  ( null? l) asks if the argument l is the null list. . What is the next question? ( atom ? ( car l ) ) . . the value of the application is true. . l is not the null list. In this case. and (define . . If it is not .(define lat ?1 (lambda (l) (cond ( ( null ? l) #t ) ( ( atom ? ( car l)) ( lat ? ( cdr l))) (else #f ) ) ) ) What i s the value of ( lat ? l ) where l is the argument (bacon and eggs) #t . 16 Chapter 2 . 1 L: (defun 1at? (1} (cond ( (null 1} t} ( (atom? (car 1} } (lat? (cdr 1} } } ( t nil} } } How do we determine the answer # t for the application ( lat ? l) You were not expected to know this one either. ) gives it a name. The application ( lat ? l) where l is (bacon and eggs) has the value #t truebecause l is a lat . ) creates a function. (lambda . we ask the next question. ) asks questions. The answer is determined by answering the questions asked by latf Hint: Write down the definition of the function lat ? and refer to it for the next group of questions. so we ask the next question. What is the first question asked by ( lat ? l) ( null? l) Note: (cond . . If it is. .
What is the meaning of the line ( ( atom ? ( car l)) ( lat? ( cdr l))) where l is (and eggs) ( atom ? ( car l)) asks i f ( car l) i s an atom . and Again. If it is. so the value of the function is the value of ( lat ? ( cdr l ) ) . which is (eggs). What is the meaning of ( lat ? ( cdr l)) ( lat ? ( cdr l)) finds out if the rest of l is composed only of atoms. Do It Again. In this case. In this case. we want to know if the rest of l is also composed only of atoms. What is the next question? ( null ? l). so we want to find out if the rest of the list l is composed only of atoms. l is not the null list . we ask the next question. with the argument ( cdr l ) . If ( car l) is an atom . What is the meaning of the line (( null? l) #t ) where l is now (and eggs) ( null ? l) asks if the argument l is the null list . . .What is the meaning of the line (( atom ? ( car l)) ( lat? ( cdr l))) where l is (bacon and eggs) ( atom ? ( car l)) asks if the first Sexpression of the list l is an atom . by referring to the function with a new argument . What is the next question? ( atom ? ( car l ) ) . If ( car l) is not an atom. the value of the application is ( lat ? ( cdr l ) ) . we ask the next question . If not . we ask the next question. ( car l) is an atom . ( car l) is an atom . Do It. Now what is the argument l for lat ? Now the argument l is ( cdr l ) . which is (and eggs) . but this time. What is the meaning of ( lat? ( cdr l)) ( lat ? ( cdr l)) finds out i f the rest of the list l is composed only of atoms. the value of the application is #t . by referring again to the function lat ?. In this case. 17 . so we ask the next question. If it is an atom . If it is not . and Again .
ask the next question. move to the next question. If ( car l) is not an atom. What is the meaning of ( lat ? ( cdr l)) ( lat ? ( cdr l)) finds out if the rest of the list l is composed only of atoms. l is not null. D o you remember the question about ( lat ? l) Probably not . If it is. with l becoming the value of ( cdr l ) . is #t true. ( car l) is an atom . What is the meaning of the line ( ( atom? ( car l)) ( lat ? ( cdr l))) where l is now (eggs) ( atom ? ( car l)) asks i f ( car l) i s an atom. what is the argument for lat ? () . In this case. by referring to the function lat ?. so we ask the next question. So. () is the null list. The application ( lat? l) has the value #t if the list l is a list of atoms where l is (bacon and eggs) . the value of the application ( lat ? l) where l is (bacon and eggs) . What is the meaning of the line ( ( null ? l) #t ) where l is now ( ) ( null ? l) asks if the argument l is the null list . we ask the next question. What is the next question? ( atom ? ( car l ) ) . the value of the application is ( lat ? ( cdr l ) ) . the value of the application is the value of #t . Now. In this case.What is the next question? ( null? l ) . If it is. In this case. If not . the value of the application is #t true. What is the meaning of the line ( ( null? l) #t ) where l is now (eggs) ( null? l) asks i f the argument l i s the null list . so once again we look at ( lat? ( cdr l)). If it is. 18 Chapter 2 . If it is not.
since the list l contains an Sexpression that is a list . and asks if each Sexpression is an atom. so we want to check if the rest of the list l is composed only of atoms. Do It. If it runs out without encountering a list . the value is #t . What is the meaning of the line ( ( atom ? ( car l)) ( lat ? ( cdr l))) where l is (bacon (and eggs)) ( atom ? ( car l)) asks i f ( car l) i s a n atom . What is the meaning of the line ( ( null? l) #t ) where l is (bacon (and eggs)) ( null ? l) asks i f l is the null list . the value is ( lat ? ( cdr l ) ) . 19 . What is the first question? ( null ? l ) . What is the next question? ( atom ? ( car l ) ) . move to the next question. If it is not . In this case.. If l is not null. we ask the next question. If it is. it is not null. the value is #t . In this case.Can you describe what the function lat ? does in your own words? Here are our words: "lat ? looks at each Sexpression in a list . If it finds a list . and Again ." consider the next few questions. in turn. the value is #ffalse. ( car l) is an atom . and Again. Do It Again. so we ask the next question. This is the function lat ? again: (define lat ? (lambda (l) (cond ( ( null? l) #t ) ( ( atom ? ( car l)) ( lat ? ( cdr l))) (else #f)))) What is the value of ( lat? l) where l is now (bacon (and eggs)) #f." To see how we could arrive at a value of "false.. until it runs out of Sexpressions . I f i t i s .
If it is null. the value is #t . What is the meaning of the line ( ( null? l) #t ) where l is now ((and eggs) ) ( null? l) asks if l is the null list. What is the next question? else. the value is ( lat ? ( cdr l)). If it is not null. by referring to lat ? with l replaced by ( cdr l). If else is trueas it always isthen the answer is #ffalse. can have an atom in the first position. If it is not . ( car l) is not an atom . 20 Chapter 2 . or can have a list in the first position . Because we do not need to ask any more questions. so move to the next question. because the question else is always true! What is the meaning of the question else Is else true? else Why is else the last question? Of course. In this case. Why do we not need to ask any more questions? Because a list can be empty. else asks if else is true.What is the meaning of ( lat ? ( cdr l)) ( lat ? ( cdr l)) checks to see if the rest of the list l is composed only of atoms. In this case. l is not null. so we ask the next question . What is the meaning of the line (else #f ) else asks if else is true. If it is. What i s the next question? ( atom ? ( car l)). we ask the next question. we move to the next question. What is the meaning of the line ( ( atom ? ( car l)) ( lat ? ( cdr l))) where l is now ( (and eggs)) ( atom ? ( car l)) asks if ( car l) is an atom. Yes.
21 .. Do It. " Is ( or ( null? ll ) ( atom ? l2 ) ) true or false where l1 is () and l2 is (d e f g) True.. and Again . If it finds a list . .. . because ( null ? l1 ) is true where l1 is ( ) . If the first one is true it stops and answers true. Can you describe how we determined the value #f for ( lat? l) where l is ( bacon (and eggs)) Here is one way to say it : "( lat? l) looks at each item in its argument to see if it is an atom . What does ( or .What is ))) These are the closing or matching parentheses of ( cond . . the value of ( lat ? l) is #f. (lambda . . one at a time. . which appear at the beginning of a function definition. Do It Again. because ( null ? l2) is true where l2 is ( ) . Otherwise it asks the second question and answers with whatever the second question answers. . . . because neither ( null? l1 ) nor ( null? l2 ) is true where l1 is (a b c) and l2 is (atom ) . as it did in the example ( bacon (and eggs) ) . If it runs out of items before it finds a list . . False. . and (define . ) do? ( or . ) asks two questions. and Again. . the value of ( lat ? l) is #t . . Is ( or ( null? l1 ) ( null? l2 ) ) true or false where l1 is (a b c) and l2 is () Is ( or ( null? l1 } ( null? l2 ) ) true o r false where l1 is (a b c) and l2 is (atom ) True.
(mashed potatoes and meat gravy) . 22 Chapter 2 . What is the first question asked by ( member? a lat) ( null? lat ) . (coffee tea or milk) is the same as the atom atea . because one of the atoms of the lat. How do we determine the value #t for the above application? The value is determined by asking the questions about ( member? a lat).Is it true or false that a is a member of lat where a is tea and lat is (coffee tea or m i l k) True. Hint : Write down the definition of the function member? and refer to it while you work on the next group of questions. Is ( member? a lat) true or false where a is poached and lat is (fried eggs and scra m bled eggs) False. because the atom meat is one of the atoms of lat . This is the function member? (define member? (lambda (a lat) ( cond ( ( null ? lat) #f ) (else ( or ( eq? ( car lat) a) ( member? a ( cdr lat) ) ) ) ) ) ) What i s the value of ( member? a lat) where a is m eat and lat is ( mashed potatoes and meat gravy) #t . since a is not one of the atoms of the lat. This i s also the first question asked b y lat ?.
Do It Again. we ask the next question. Is else really a question? Yes. The answer ( or ( eq? ( car lat) a) ( member? a ( cdr lat ) ) ) does this. we have to find out whether the car of lat is the same atom as a. and Again . the value is #f.The First Commandment (preliminary) Always ask null ? as the first question in expressing any function. True or false: ( or ( eq? ( car lat) a) ( member? a ( cdr lat))) where a is meat and lat is (mashed potatoes and meat gravy) We will find out by looking at each question in turn. What is the meaning of the line (else ( or ( eq ? ( car lat) a) ( member? a ( cdr lat)))) Now that we know that lat is not null ?. . it is not null. In this case. and Again. Why is else the next question? Because we do not need to ask any more questions. or whether a is somewhere in the rest of lat. If it is. . since the atom meat was not found in lat. What is the meaning of the line ((null? lat) #f ) where lat is (mashed potatoes and meat gravy) ( null? lat) asks if lat is the null list . What is the next question? else. else is a question whose value is always true. 23 . so we ask the next question. If not . Do It.
What do we do now? Ask the next question. ) ( member? a ( cdr lat ) ) . Is a eq ? to the car of lat No. because a is meat and the car of lat is potatoes.Is ( eq ? ( car lat) a) true or false where a is meat and lat is (mashed potatoes and meat gravy) False. the car of (mashed potatoes and meat gravy) . 24 Chapter 2 . specifically ( potatoes and meat gravy). Remember The First Commandment.. What is the second question of ( or . Now what are the arguments of member? a is meat and lat is now ( cdr lat) . What is the next question? else.. Is ( null ? lat) true or false where lat is (potatoes and meat gravy) #ffalse. because meat is not eq ? to mashed . What is the meaning of ( or ( eq ? ( car lat) a) ( member? a ( cdr lat))) ( or ( eq ? ( car lat) a) ( member? a ( cdr lat))) finds out if a is eq ? to the car of lat or if a is a member of the cdr of lat by referring to the function. What is the next question? ( null ? lat ) . This refers t o the function with the argument lat replaced by ( cdr lat).
What are the new arguments? a is meat. and lat is (and meat gravy) . What is the next question? else. Do It. ask the next question. What do we do now? Recurrefer to the function with new arguments. . since ( null ? lat) is false. and Again . Do It Again. and lat is (meat gravy) . what are the arguments of member? a i s meat. 25 . What is the next question? else. . What is the next question? ( null ? lat ) . Why? Because ( eq ? ( car lat) a) i s false. and Again. What is the value of ( or ( eq? ( car lat) a) ( member? a ( cdr lat))) The value of ( member? a ( cdr lat ) ) . What is the next question? ( null ? lat ) . Now.So what do we do next? We ask ( member ? a ( cdr lat ) ) . What d o we do now? Since ( null? lat) is false. What do we do now? Ask the next question .
are the same atom.What is the value of ( or ( eq ? ( car lat) a) ( �e�ber? a ( cdr lat))) #t . #t ... Move to the next line. ( null? lat ) No. #t . What is the value of the application ( �e�ber? a lat ) where a is meat and lat is ( m eat gravy) What is the value of the application ( �e�ber? a lat) where a is meat and lat is (and meat gravy) What is the value of the application ( �e�ber? a lat) where a is meat and lat is ( potatoes and meat gravy) What is the value of the application ( �e�ber? a lat ) where a is meat and lat is ( m ashed potatoes and meat gravy) Just to make sure you have it right . Of course. ( or . because meat is also a member of the lat (and meat gravy) . this is our original lat. #t. which is meat. because meat is also a member of the lat (mashed potatoes and meat gravy). Therefore. 26 Chapter 2 . which is meat . What is the value of ( �e�ber? a lat) where a is meat and lat is (mashed potatoes and meat gravy) #t . because we have found that meat is a member of ( m eat gravy). #t . ) answers with #t . because meat is also a member of the lat ( potatoes and meat gravy). because ( car lat ) . and a. let 's quickly run through it again . Hint : Write down the definition of the function �e�ber? and its arguments and refer to them as you go through the next group of questions.
Recur with a and ( cdr lat) where a is meat and ( cdr lat) is (and meat gravy) . else Yes. ( null? lat) No. Recur with a and ( cdr lat) where a is meat and ( cdr lat) is (meat gravy). ( or ( eq? ( car lat) a) ( member? a ( cdr lat))) ( eq? ( car lat) a) No. ( eq? ( car lat) a) Yes. else Yes. Perhaps. What next? Recur with a and ( cdr lat) where a is meat and ( cdr lat) is ( potatoes and meat gravy) . Ask the next question. Do It Again. the value is #t . Move to the next line. ( null ? lat) No. . but ( eq ? ( car lat) a) is false. Move to the next line. Do It. . 27 . Move to the next line. ( null? lat) No. and Again .else Yes. and Again. but ( eq ? ( car lat) a) is false.
What is the value of ( memberP a lat) where a is meat and lat is (mashed potatoes and meat gravy) #t . ( null? lat) No. What i s the value o f ( memberP a lat) where a is meat and lat is (meat gravy) #t . Move t o the next line. 28 Chapter 2 . What is the value of ( memberP a lat) where a is meat and lat is (and meat gravy) #t . What is the value of ( member? a lat) where a is meat and lat is ( potatoes and meat gravy) #t . What 's the first question member? asks? ( nu ll? lat) . Let 's work out why it is #f. What is the value of ( memberP a lat) where a is liver and lat is ( bagels and lox) #f.( or ( eq P ( car lat) a) ( memberP a ( cdr lat) ) ) #t .
but ( eq ? ( car lat) a) is false. 29 . Yes. ( null? lat) No. . else Yes. Do It. What is the value of ( or ( eq? ( car lat) a) ( member? a ( cdr lat))) where a is liver and lat is ( lox) #f.else Yes. Move to the next line. but ( eq ? ( car lat) a) is still false. ( null? lat) No. Recur with a and ( cdr lat) where a is liver and ( cdr lat) is (lox) . . Recur with a and ( cdr lat) where a is l iver and ( cdr lat) is () . Do It Again. but ( eq ? ( car lat) a) is false. Move to the next line. else Yes. and Again. Recur with a and ( cdr lat) where a is l iver and ( cdr lat) is (and lox) . ( null? lat) What is the value of ( member? a lat) where a is liver and lat is () #f. and Again .
30 Chapter 2 . What is the value of ( or ( eq ? ( car lat) a) ( member? a ( cdr lat))) where a is l iver and lat is (bagels and lox) #f . What is the value of ( or ( eq ? ( car lat) a) ( member? a ( cdr lat))) where a is l iver and lat is (and lox) #f .What is the value of ( member? a lat) where a is liver and lat is (lox) #f. What is the value of ( member? a lat) where a is l iver and lat is (and lox) #f. What is the value of ( member? a lat) where a is l iver and lat is (bagels and lox) #f .
31 . Do It Again. and Again .Do you believe all this? Then you may rest! This space for doodling Do It. . . and Again.
.
Return () . Is there any other question we should ask about the lat? Cons the Magnificent 33 . No.What is ( rember a lat) where a is mint and lat is (lamb chops and mint jelly) (lamb chops and jelly) "Rember" stands for remove a mem ber. What steps should we use to do this? First we will test ( null? lat)The First Commandment . Either a lat is empty or it contains at least one atom. And if ( null? lat) is true? What do we know if ( null? lat) is not true? We know that there must be at least one atom in the lat . What does ( rember a lat) do? It takes an atom and a lat as its arguments. ( rember a lat) where a is mint and lat is (lamb chops and mint flavored mint jelly) (lamb chops and flavored mint jelly) . ( rember a lat) where a is toast and lat is (bacon lettuce and tomato) (bacon lettuce and tomato). ( rember a lat) where a is cup and lat is (coffee cup tea cup and hick cup) (coffee tea cup and hick cu p). and makes a new lat with the first occurrence of the atom in the old lat removed.
Now.)) . Hint : Write down the function rember and its arguments.) ( .What do we do if we know that the lat contains at least one atom? How do we ask questions? We ask whether a is equal to ( car lat ). What do we do if a is not the same as ( car lat ) We want to keep ( car lat). let 's write down what we have so far: (define rember (lambda (a lat) (cond ( ( null? lat ) (quote ( ))) (else ( c ond ( ( eq ? ( car lat) a) ( cdr lat)) (else ( rember a ( cdr lat)))))))) What is the value of ( rember a lat ) where a is bacon and lat is ( bacon lettuce and tomato) ( l ettuce and tomato). What would be the value of ( rember a lat) if a were the same as ( car lat) ( cdr lat). No. and refer to them as you go through the next sequence of questions. _ __ How do we ask if a is the same as ( car lat) ( eq ? ( car lat ) a). but also find out if a is somewhere in the rest of the lat . By using ( c ond ( .. How d o we remove the first occurrence of a in the rest of lat Is there any other question we should ask? ( rember a ( cdr lat)). 34 Chapter 3 .
What is the value of ( rember a lat) where a is and and lat is (bacon lettuce and tomato) ( bacon lettuce tomato). because it is the original list without the atom bacon. What is the first question? ( null ? lat) . so the value is ( cdr lat) . Cons the Magnificent 35 . let 's see if this function works. But did we really use a good example? Who knows? But the proof of the pudding is in the eating. What next? Ask the next question. ( eq? ( car lat) a) Yes. What do we do now? We compare each atom of the lat with the atom a. it is the list (lettuce and tomato) . What do we do now? Move t o the next line and ask the next question. In this case. What does rember do? It takes an atom and a lat as its arguments.Now. and makes a new lat with the first occurrence of the atom in the old lat removed. so let 's try another example. Is this the correct value? Yes. else Yes. and if the comparison fails we build a list that begins with the atom we just compared.
else Sure. and ask the next question. so ask the next question. What is the first question asked by rember ( null? lat). and ask the next question. else ( eq? ( car lat) a) Okay. ( null ? lat) No. What do we do now? Move to the next line. else Of course. ( eq ? ( car lat) a) What is the meaning of ( rember a ( cdr lat) ) Recur where a is and and ( cdr lat) is (and tomato) . What is the meaning of (else ( rember a ( cdr lat))) else asks if else is trueas it always isand the rest of the line says to recur with a and ( cdr lat) . No. No. where a is and and ( cdr lat) is (lettuce and tomato) . 36 Chapter 3 .Let us see if our function rember works. so move to the next line. so move to the next line. so move to the next line. ( null ? lat) No. so move to the next line.
since (tomato) is not the list (bacon lettuce and tomato) with j ust aandremoved. but we also lost all the atoms preceding and. from chapter 1 ? The Second Commandment Use cons to build lists. How can we keep from losing the atoms bacon and lettuce We use Cons the Magnificent . What did we do wrong? We dropped and . Cons the Magnificent 37 . So what is the result? ( cdr l at)(tomato) . Let 's see what happens when we use cons (define rember (lambda (a lat) ( cond ( ( n·ull? lat) (quote ())) (else (cond (( eq ? ( car lat) a) ( cdr lat) ) (else ( cons ( car lat) ( rember a ( cdr lat) ) ) ) ) ) ) ) ) What i s the value o f ( rember a lat) where a is and and lat is (bacon lettuce and tomato) ( bacon lettuce tomato) . Is this correct? No.( eq? ( car lat) a) Yes. Remember cons . Hint : Make a copy of this function with cons and the arguments a and lat so you can refer to it for the following questions.
so move to the next line. else Yes. ( eq ? ( car lat) a) No. we must find it before we can cons ( car lat) onto it. B u t since we don 't know the value of ( rember a ( cdr lat) ) yet . What is the meaning of ( rember a ( cdr lat) ) This refers to the function with lat replaced by ( cdr lat) ( lettuce and tomato) . of course. ( eq ? ( car lat) a) No. we must find it before we can cons ( car lat) onto it .  ( null ? lat) No. What do we do now? Ask the next question. ask the next question. else Yes. so move to the next line. 38 Chapter 3 . so move to the next line.What is the first question? ( null? lat ) . B u t since we don 't know the value of ( rember a ( cdr lat)) yet . What is the meaning of ( cons ( car lat) ( rember a ( cdr lat))) It says to cons the car of latlettuceonto the value of ( rember a ( cdr lat ) ) . What is the meaning of ( cons ( car lat) ( rember a ( cdr lat))) where a is and and lat is ( bacon lettuce and tomato) It says to cons the car of latbacononto the value of ( rember a ( cdr lat ) ) .
(and tomato). we can cons lettuce onto it . Certainly not ! We know what ( rember a lat ) is when lat is (and tomato) . ( null? lat) else ( eq? ( car lat) a) What is the value of the line ( ( eq? ( car lat) a) ( cdr lat)) Are we finished? ( cdr lat)  ( tomato ) . Cons the Magnificent 39 . No. when lat is (lettuce and tomato) and ( rember a ( cdr lat )) is (tomato) . Now that we have this value. We now have a value for ( rember a ( cdr lat) ) where a i s and and ( cdr lat) is (and tomato) This value is (tomato) What next? What is the result when we cons lettuce onto (tomato) What does (lettuce tomato) represent? (lettuce tomato). Still. Recall that we wanted to cons lettuce onto the value of ( rember a ( cdr lat )) where a was and and ( cdr lat ) was (and tomato) .What is the meaning of ( rember a ( cdr lat )) This refers to the function with lat replaced by ( cdr lat ) . It represents the value of ( cons ( car lat ) ( rember a ( cdr lat ) ) ) . that is. Yes. but we don't yet know what it is when lat is (lettuce and tomato) or ( bacon lettuce and tomato). which is (tomato) . so ask the next question.
we can cons bacon onto it. Lunch? Are we finished yet? Yes." 40 Chapter 3 . we saved it to be consed to the final value later. which is (lettuce tomato) . Now that we have this value. one at a time. Can you put in your own words how we determined the final value ( bacon lettuce tomato) In our words: "The function rember checked each atom of the lat . and consed the previous atoms back onto the rest of the lat. we wanted to cons bacon onto the value of ( rember a ( cdr lat)). When rember found the atom and. but we don't yet know what it is when lat is (bacon lettuce and tomato) . so what must we do again? Recall that . ( bacon lettuce tomato) . at one time. where a was and and ( cdr lat) was (lettuce and tomato) . What is the result when we cons bacon onto ( l ettuce tomato) What does ( bacon lettuce tomato) represent? t t It represents the value of ( cons ( car lat) ( rember a ( cdr lat))).Are we finished yet? Not quite. it dropped it. So far we know what ( rember a lat) is when lat is (lettuce and tomato). to see if it was the same as the atom and. when lat is ( bacon lettuce and tomato) and ( rember a ( cdr lat)) is (lettuce tomato) . We now have a value for ( rember a ( cdr lat)) where a is and and ( cdr lat) is ( l ettuce and tomato) This value is (lettuce tomato) This is not the final value. If the car was not the same as the atom .
we can simplify it. ( eq? ( car lat) a) No. Hint : Write down the function rember and its arguments and refer to them as you go through the next sequence of questions. so the value is ( cons ( car lat) ( rember a ( cdr lat ) ) ) . What is the meaning of ( cons ( car lat) ( rember a ( cdr lat))) This says t o refer t o the function rember but with the argument lat replaced by ( cdr lat) .  Cons the Magnificent 41 . and that after we arrive at a value for ( rember a ( cdr lat) ) we must cons ( car lat ) bacononto it. Let's see if the new rember is the same as the old one. What is the value of the application ( rember a lat) where a is and and lat is (bacon lettuce and tomato) (bacon lettuce tomato) .Can you rewrite rember so that it reflects the above description? Yes. So why don't we simplify right away? Because then a function 's structure does not coincide with its argument 's structure. else Yes. (defi ne rember (lambda ( a lat) ( c o nd ( ( null ? lat) (quote ( ) ) ) ( ( eq ? ( car lat) a) ( cdr lat ) ) (els e ( cons ( car lat) ( rember a ( cdr lat ) ) ) ) ) ) ) Do you think this is simpler? Functions like rember can always be simplified in this manner. ( null? lat) No.
and that after we arrive at a value for ( rember a ( cdr lat) ) .  baco nonto Now that we have completed rember try this example: ( rember a lat) where a is sauce and lat is (soy sa uce and tomato sauce) ( rember a lat) is (soy and tomato sauce) . 42 Chapter 3 . Now what? Now cons ( car lat ) (lettuce tomato) . Now what? Now cons ( car lat)lettuceonto (tomato) . ( null ? lat) No. so the value is ( cons ( car lat) ( rember a ( cdr lat))). else Yes. ( eq ? ( car lat ) a) No.( null ? lat) No. with the argument lat replaced by ( cdr lat) . we must cons ( car lat )lettuceonto it. What is the meaning of ( cons ( car lat) ( rember a ( cdr lat ))) This says we recur using the function rember. What is the value of the line ( ( eq ? ( car lat) a) ( cdr lat) ) It is ( cdr lat)(tomato) . ( eq ? ( car lat) a) Yes.
What is (firsts l ) where l is ( ( (five plu ms) four) (eleven green oranges) ((no) more)) ( (five plu ms) eleven (no) ) . What is (firsts l ) where l is ((a b) (c d) (e f) ) (a c e ) . which is either a null list or contains only nonempty lists. It builds another list composed of the first Sexpression of each internal list . what does (firsts l ) do? We tried the following: "The function firsts takes one argument . (five four eleven) . a list.What is (firsts l ) where l is ( (apple peach pumpkin) (plum pear cherry) (grape raisi n pea ) (bean carrot eggplant)) (apple p l u m gra pe bea n ) . In your own words. What is (firsts l ) where l is () What i s (firsts l ) where l is ( (five plu ms) (four) (eleven green oranges)) ()." Cons the Magnificent 43 .
. Because we can only look at one Sexpression at a time. Why ( cons Because we are building a listThe Second Commandment . 44 Chapter 3 . or it contains at least one nonempty list. we must recur. ) Because we need to ask questions about the actual arguments. )) Because we always state the function name. and they always appear at the end of a function definition. . . . and (define. To look at the rest. (lambda. Why (firsts ( cdr l)) Why ) ) ) Because these are the matching parentheses for ( cond. ) (else ( cons . . Why (else Because we only have two questions to ask about the list l: either it is the null list . . And because the last question is always else. ) The First Commandment. Why ( ( null ? l) .See if you can write the function firsts Remember the Commandments! This much is easy: (define firsts (lambda (l) (cond ( ( null? l) . . (firsts ( cdr l))))))) Why (define firsts (lambda (l) . (lambda. . . . and the argument ( s ) of the function . Why (else See above. Why (cond .
d .Keeping in mind the definition of (firsts l) what is a typical element of the value of (firsts l) where l is ((a b) ( c d) ( e f) ) a. and then cons it onto the natural recursion. See chapter 1 . The Third Commandment When building a list. ._______. o r even e. With The Third Commandment . we can now fill in more of the function firsts What does the last line look like now? (else ( cons ( car ( car l)) (firsts ( cdr l)) ) ) . How do we describe a typical element for (firsts l) As the car of an element of l( car ( car l ) ) .. When we find a typical element of (firsts l) what do we do with it? cons i t onto the recursion(firsts ( cdr l ) ) . Consider the function seconds What would be a typical element of the value of ( seconds l) where l is (( a b) ( c d) ( e f) ) b. or f. describe the first typical ele ment. typical element natural recursion Cons the Magnificent 45 . What is another typical element? c.
so move to the next line. . ) (else ( cons ( car ( car l)) (firsts ( cdr l ) ) ) ) ) ) ) where l is ( ( a b) ( c d ) ( e f) ) Nothing yet . What is the meaning of ( cons ( car ( car l)) (firsts ( cdr l))) Save ( car ( car l)) . and recur with (firsts ( cdr l)). What is the meaning of ( cons ( car ( car l)) (firsts ( cdr l))) It saves ( car ( car l ) ) to cons onto (firsts ( cdr l ) ) .What does (firsts l) do (define firsts (lambda (l) (cond ( ( null? l) . and recur with (firsts ( cdr l)). 46 Chapter 3 . ( null ? l) where l is ( ( c d) ( e f) ) No. What is the meaning of ( cons ( car ( car l)) (firsts ( cdr l))) Save ( car ( car l ) ) . . however. Now. We can. what is the value of the line ( ( null ? l) . To find (firsts ( cdr l ) ) . so move t o the next line. ( null? l) where l is ( ( e f) ) No . ( null ? l) where l is ( ( a b) ( c d) ( e f) ) No. something is missing. The first line ( ( nu ll ? l ) . We are still missing one important ingredient in our recipe. proceed without it for now. . ) needs a value for the case where l is the null list . . we refer to the function with the new argument ( cdr l ) . ( null ? l) Yes. ) There is no value. . so move to the next line. .
what is the value of (firsts l) With which of the three alternatives do you feel most comfortable? What is ( insertR new old lat) where new is topping old is fudge and lat is (ice cream with fudge for dessert) ( insertR new old lat) where new is jalapeno old is and and lat is (tacos tamales and sa lsa) Correct ! Now you should use that one. or 1 . We need to: I. cons c onto the value of 3 3. (tacos tama les a n d jalapeno sa lsa ) . Cons the Magnificent 47 . cons a onto the value of 2 2. we cannot use #t or #f. Remember The Law of Cons. cons c onto the value of 1 3. For the purpose of cons ing. Since the final value must be a list . either 1. cons e onto () 2. (a c e) . (ice crea m with fudge topping for dessert ) . what value can we give when ( null? l) is true? With () as a value. cons e onto () Ill or cons a onto the cons of c onto the cons of e onto () In any case. Let 's try (quote ( ) ) .What do we need to cons atoms onto? A list . cons a onto the value of 2 II. we now have three cons steps to go back and pick up.
) ) ) Which argument changes when we recur with insertR How many questions can we ask about the lat? lat . Two.( insertR new old lat) where new is e old is d and lat is (a b c d f g d h ) (a b c d e f g d h). because we can only look a t one of its atoms at a time. because else is always the last question. Which questions do we ask? First . The function insertR builds a lat with new inserted to the right of the first occurrence of old . . Second. A lat is either the null list or a nonempty list of atoms. " See if you can write the first three lines of the function insertR (define insertR (lambda ( new old lat) (cond . what does ( insertR new old lat) do? I n our words: "It takes three arguments: the atoms new and old . 48 Chapter 3 . and a lat . What do we know if ( null? lat) is not true? We know that lat has at least one element . I n your own words. we ask ( eq ? ( car lat) old ) . Which questions do we ask about the first element? First . we ask else. Then we ask else. we ask ( null? lat) . because there are no other interesting cases. .
w e want Let 's try con s ing new onto ( cdr lat) .Now see if you can write the whole function inserlR Here i s our first attempt . When ( car lat) i s the same to insert new to the right . Yes. (define inserlR (lambda ( new old lat) (cond <  (else (cond < <  __  ) )))))) (define inserlR (lambda ( new old lat) (cond ( ( null? lat) (quote ( ) ) ) (else (cond ( ( eq ? ( car lat) old ) ( cdr lat) ) (else ( cons ( car lat) ( inserlR new old ( cdr lat) ) ) ) ) ) ) ) ) What i s the value of the application ( inserlR new old lat) that we just determined where new is topping old is fudge and lat is (ice crea m with fudge for dessert) So far this is the same as rember What do we do in inserlR when ( eq? ( car lat) old ) is true? How is this done? Now we have (ice crea m with for dessert ) . as old. (define inserlR (lambda ( new old lat) (cond ( ( null? lat) (quote ( ) ) ) (else (cond ( ( eq? ( car lat) old ) ( cons new ( cdr lat))) (else ( cons ( car lat) ( inserlR new old ( cdr lat ) ) ) ) ) ) ) ) ) Cons the Magnificent 49 .
we have only replaced fudge with topping. How can we include old before new Now let 's write the rest of the function insertR (define insertR (lambda ( new old lat) (cond ( ( null ? lat) (quote ( ) ) ) (else (cond ( ( eq? ( car lat) old) ( cons old ( cons new ( cdr lat)))) (else ( cons ( car lat) ( insertR new old ( cdr lat))))))))) When new is topping. and lat is (ice crea m with fudge for dessert ) . the value of the application. 50 Chapter 3 . ( insertR new old lat ) . If you got this right . Try consing old onto ( cons new ( cdr lat)). What still needs to be done? Somehow we need to include the atom that is the same as old before the atom new.So what is ( insertR new old lat) now where new is topping old is fudge and lat is (ice crea m with fudge for dessert) (ice crea m with topping for dessert). is (ice cream with fudge topping for dessert). Is this the list we wanted? No. have one. old is fudge.
(define subst (lambda ( new old lat) ( cond ( ( null? lat) ( quote ( ) ) ) ( else ( cond ( ( eq ? ( car lat) old ) ( cons new ( cdr lat ) ) ) ( else ( cons ( car lat) ( subst new old ( cdr lat ) ) ) ) ) ) ) ) ) This i s the same as one of our incorrect attempts at insertR. Now try subst Hint: (subst new old lat) replaces the first occurrence of old in the lat with new For example. right? (define insertL (lambda ( new old lat) (cond ( ( null ? lat) (quote ( ) ) ) (else (cond ( ( eq ? ( car lat) old ) ( cons new ( cons old ( cdr lat ) ) ) ) (else ( cons ( car lat) ( insertL new old ( cdr lat ) ) ) ) ) ) ) ) ) Did you think of a different way to do it? For example. Obviously. ( ( eq ? ( car lat) old ) ( cons new ( cons old ( cdr lat ) ) ) ) could have been ( ( eq ? ( car lat) old ) ( cons new lat) ) since ( cons old ( cdr lat) ) where old i s eq ? to ( car lat) is the same as lat.Now try insertL Hint: insertL inserts the atom new to the left of the first occurrence of the atom old in lat This much is easy. Cons the Magnificent 51 . where new is topping old is fudge and lat is (ice crea m with fudge for dessert) the value is (ice crea m with topping for dessert) Now you have the idea.
or the rest of the lat . If it is not. go and repeat the cakeconsing. rember saves the atom and proceeds. so that the value returned is the original lat . Do you recall what rember does? The function rember looks at each atom of a lat to see if it is the same as the atom a. where new is vanilla o1 is chocolate o2 is banana and lat is (banana ice cream with chocolate topping) the value is (vanilla ice cream with chocolate topping) (define subst2 (lambda ( new o1 o2 lat) (cond ( ( num' lat) (quote ())) (else (cond ( ( eq � ( car lat) o1 ) ( cons new ( cdr lat))) ( ( eq � ( car lat) o2) ( cons new ( cdr lat))) (else ( cons ( car lat) ( subst2 new o1 o2 ( cdr lat) )))))))) Did you think of a better way? Replace the two eq � lines about the ( car lat) by ( (or ( eq � ( car lat) o1 ) ( eq� ( car lat) o2 )) ( cons new ( cdr lat))).Go cons a piece of cake onto your mouth. with only that occurrence of a removed. When it finds the first occurrence of a. Now try subst2 Hint: (subst2 new o1 o2 lat) replaces either the first occurrence of o1 or the first occurrence of o2 by new For example. I f you got the last function. it stops and gives the value ( cdr lat) . 52 Chapter 3 .
(define multirember (lambda ( a lat) (cond ( (else (cond ( ( _ __ ___ ___  ) )))))) Hint : What d o we want as the value when ( eq? ( car lat) a) is true? Consider the example where a is cup and lat is (coffee cup tea cup and hick cup) Can you see how multirember works? Possibly not . Now determine ( multirember a ( cdr lat ) ) . The value of the application is (coffee tea and hick) . so move to the next line. so move to the next line. so we will go through the steps necessary to arrive at the value (coffee tea and hick) . What is the meaning of ( cons ( car lat) ( multirember a ( cdr lat))) Save ( car lat) coffee to be consed onto the value of ( multirember a ( cdr lat) ) later. w e now recur with ( multirember a ( cdr lat ) ) .  ( null? lat) No. Cons the Magnificen t 53 . ( null ? lat) No. ( define multirember (lambda ( a lat) ( cond ( ( null? lat) ( quote ())) ( else ( cond ( ( eq ? ( car lat) a) ( multirember a ( cdr lat ))) ( else ( cons ( car lat) ( multirember a ( cdr lat ) ) ) ) ) ) ) ) ) After the first occurrence o f a .Write the function multirember which gives as its final value the lat with all occurrences of a removed. else Yes. ( eq? ( car lat) a) No. in order to remove the other occurrences. s o move t o the next line.
and determine ( multirember a ( cdr lat)). so move to the next line. ( eq? ( car lat) a) No. else Yes! No. Now determine ( multirember a ( cdr lat)). ( null ? lat) No. so move t o the next line. so move to the next line. What is the meaning of ( cons ( car lat) ( multirember a ( cdr lat))) Save ( car lat) and to be consed onto the value of ( multirember a ( cdr lat) ) later. so forget ( car lat ) . so forget ( car lat).else Naturally. ( eq ? ( car lat) a) Yes. move on.  ( null ? lat) No. else Okay. so move to the next line. ( null ? lat) No. so move to the next line.  54 Chapter 3 . and determine ( multirember a ( cdr lat)). ( eq ? ( car lat) a) Yes. ( eq ? ( car lat) a) What is the meaning of ( cons ( car lat) ( multirember a ( cdr lat ) ) ) Save ( car lat) tea to be consed onto the value of ( multirember a ( cdr lat)) later. Now detennine ( multirember a ( cdr lat) ) .
s o move t o the next line. Are we finished? No. What do we do next? What do we do next? Are we finished now? Yes . We cons tea onto (and hick ) . Cons the Magnificent 55 . Now determine ( multirember a ( cdr lat ) ) . What do we do next? We cons and onto ( hick ) . and determine ( multirember a ( cdr lat ) ) . s o the value i s () . ( null? lat) Yes. we still have several conses to pick up. so move to the next line. ( eq? ( car lat) a) Yes . so move to the next line. We cons coffee onto (tea and hick ) . What is the meaning of ( cons ( car lat) ( multirember a ( cdr lat))) Save ( car lat) hick to be consed onto the value of ( multirember a ( cdr lat) ) later. so forget ( car lat) . ( eq? ( car lat) a) No.( null? lat) No.  ( null ? lat) No. What do we do next? We cons the most recent ( car lat) we havehickonto () .
Was the terminal condition ever reached? No. because we never get past the first occurrence of old. I s this function defined correctly? ( define multiinsertL (lambda ( new old lat) ( cond ( ( null ? lat) ( quote ())) ( else ( cond ( ( eq ? ( car lat) old ) ( cons new ( cons old ( multiinsertL new old lat)))) ( else ( cons ( car lat) ( multiinsertL new old ( cdr lat ) ) ) ) ) ) ) ) ) Not quite. go through ( multiinsertL new old lat) where new is fried old is fish and lat is (chips and fish or fish and fried) .Now write the function multiinsertR ( define multiinsertR (define multiinsertR (lambda ( new old lat) (cond (else (cond ( ( (  ) )))))) (lambda ( new old lat) (cond ( ( null? lat) (quote ( ))) (else ( cond ( ( eq ? ( car lat) old) ( cons ( car lat) ( cons new ( multiinsertR new old ( cdr lat) ) ) ) ) ( else ( cons ( car lat) ( multiinsertR new old ( cdr lat) )))))))) It would also be correct to use old in place of ( car lat) because we know that ( eq ? ( car lat) old ) . To find out why. 56 Chapter 3 .
test termination with null?.Now. The changing argument must be tested in the termination condition: when using cdr. Now write the function multisubst ( define multisubst (lambda ( new old lat) ( cond ( define multisubst {lambda ( new old lat) ( cond ( ( null? lat) ( quote ())) ( else ( cond ( ( eq? ( car lat) old} ( cons new ( multisubst new old ( cdr lat)))) ( else ( cons ( car lat) ( multisubst new old ( cdr lat))))))))) < ( else ( cond <  . It must be changed to be closer to termination.__ ) ) ) ) ) ) Cons the Magnificent 57 .) < . try to write the function multiinsertL again: (define multiinsertL (lambda ( new old lat) (cond <  (else (cond ( ( ) )))))) (define multiinsertL (lambda ( new old lat) (cond ( ( null? lat) (quote ( ))) ( else ( cond (( eq ? ( car lat) old} ( cons new ( cons old ( multiinsertL new old ( cdr lat))))) ( else ( cons ( car lat) ( multiinsertL new old ( cdr lat))))))))) The Fourt h Commandment (preliminary) Always change at least one argument while recurring.
9�� .
True. Are 3 and 3.Is 14 an atom? Is ( atom ? n ) true or false where n is 14 Is 3 a number? Yes. 1 L: 1S: (define aub1 Cl1111bda (n} (. because we don't need to say "where 67" when the argument is a number. 14159 numbers? Yes. but we consider only whole numbers. because all numbers are atoms.n 1 } } } } Numbers Games 59 . because 14 is an atom. 14159 a number? Yes. .e. What is ( a dd 1 1 where n is 67 n ) 1 L: 1+ S: (define add1 Cl1111bda (n} (+ n 1 } } } } What i s ( add1 67 ) Also 68. 1. Is 3. . 2. ) . . 3. 68. but we do not consider negative numbers. 0. . Yes. 4. but the only numbers we use are the nonnegative integers ( i. n is What is (sub1 1 where n is 5 n ) 4.
What is (sub1 0}
No answer. 1
( subl n ) , where n i s 0 , h as n o answer because we consider only nonnegative numbers. In practice, this result is 1.
1
Is (zero ?1 0} true or false?
True.
1
L:
zerop
Is (zero ? 1492} true or false?
False.
What is ( + 46 12}
58.
Try to write the function + Hint : It uses zero ? add1 1 and sub1 1
(define + 1 (lambda ( n m ) (cond ((zero ? m ) n) (else ( add1 ( + n (sub1
Wasn't that easy?
m
)))))))
1 Remember to use our definitions for add1 and eub 1 .
1
L, S:
This is like +. Write it as o+ (see preface) .
But didn 't we just violate The First Commandment?
Yes, but we can treat zero ? like null? since zero ? asks if a number is empty and null? asks if a list is empty.
If zero P is like null? is add1 like cons
Yes! cons builds lists and add1 builds numbers.
60
Chapter 4
What is (  14 3)
11.
What is (  17 9)
8.
What is (  18 25)
No answer. There are no negative numbers.
Try to write the function Hint: Use sub1
How about this:
(define  1 (lambda ( n m ) (cond ( ( zero ? m ) n ) (else (sub1 ( 
n
(sub1
m
)))))))
1
L, S :
This i s like  . Write i t
as o 
(see preface) .
Can you describe how (
n m
) works?
I t takes two numbers as arguments, and reduces the second until it hits zero. It subtracts one from the result as many times as it did to cause the second one to reach zero. Yes: tup is short for tuple.
Is this a tup? (2 11 3 79 47 6)
Is this a tup? (8 55 5 555)
Yes, of course, it is also a list of numbers.
Is this a tup? (1 2 8 apple 4 3)
No, it is just a list of atoms.
Is this a tup? (3 (7 4) 13 9)
No, because it is not a list of numbers. (7 4) is not a number.
Numbers Games
61
Is this a tup? ()
Yes, it is a list of zero numbers. This special case is the empty tup.
What is ( addtup tup) where tup is (3 5 2 8)
18.
What is ( addtup tup) where tup is (15 6 7 12 3)
43.
What does addtup do?
It builds a number by totaling all the numbers in its argument.
What is the natural way to build numbers from a list?
Use + in place of cons : + builds numbers in the same way as cons builds lists.
When building lists with cons the value of the terminal condition is () What should be the value of the terminal condition when building numbers with +
0.
What is the natural terminal condition for a list? What is the natural terminal condition for a tup?
( null? l).
( null? tup).
When we build a number from a list of numbers, what should the terminal condition line look like? What is the terminal condition line of addtup
( ( null ? tup) 0) , just as ( ( null? l) (quote ())) is often the terminal condition line for lists.
( ( null? tup) 0).
62
Chapter 4
How is a lat defined?
It is either an empty list , or it contains an atom , ( car lat) , and a rest, ( cdr lat) , that is also a lat .
How is a tup defined?
It is either an empty list , or it contains a number and a rest that is also a tup.
What is used in the natural recursion on a list?
( cdr lat ) .
What is used in the natural recursion on a tup?
( cdr tup ) .
Why?
Because the rest o f a nonempty list i s a list and the rest of a nonempty tup is a tup.
How many questions do we need to ask about a list?
Two.
How many questions do we need to ask about a tup?
Two, because it is either empty or it is a number and a rest, which is again a tup.
How is a number defined?
It is either zero or it is one added to a rest, where rest is again a number.
What is the natural terminal condition for numbers?
(zero ? n ) .
What is the natural recursion on a number?
( sub1
n .
)
How many questions do we need to ask about a number?
Two.
Numbers Games
63
64 Chapter 4 . and the last line of the function rember: ( cons ( car lat ) ( rember a ( cdr lat ) ) ) . ask two questions about it: (zero ? n) and else. ) ) ) ) Here is what we filled in: ( + ( car tup) ( addtup ( cdr tup))). n .The F irst Commandment (first revision) When recurring on a list of atoms. What does cons do? What does addtup do? It builds lists. . Notice the similarity between this line. What is the terminal condition line of addtup ( ( null? tup) 0) . ask two questions about it: ( null ? lat) and else. lat. What is the natural recursion for addtup ( addtup ( cdr tup ) ) . What i s ( x 5 3) What is ( x 13 4) 15. When recurring on a number. What does addtup use to build a number? I t uses + . 52. too! Fill in the dots in the following definition : (define addtup (lambda ( tup) (cond ( ( null ? tup) 0) (else . . It builds a number by totaling all the numbers in a tup. because + builds numbers.
The Fourt h Commandment (first revision) Always change at least one argument while recurring. n up m What is the terminal condition line for x ((zero P m ) 0) . What is another name for ( x this case? n ( sub1 m )) in It's the natural recursion for x.What does ( x n m ) do? It builds up a number by adding times. test termination with zero ?. Since (zero P m ) is the terminal condition. It must be changed to be closer to termination. Try to write the function x (define x 1 (lambda ( n m ) (cond ((zero P m ) 0) (else ( + n ( x n (sub1 m ))))))) 1 L. because n x 0 = 0. What function is used to do this? sub1 . m must eventually be reduced to zero. Numbers Games 65 . The changing argument must be tested in the termination condition: when using cdr. test termination with null? and when using sub1 . S: This i s like • .
but let 's follow through the function one time to see how we get this value. because (zero ? m ) is now true.What is ( x 12 3) 36. (zero ? m ) No. (zero ? m ) No. If x is correct then ( x 12 ( sub1 3)) should be 24. What are the new arguments of ( x n m) n is 12. and m is 1 . What is the meaning of (+ n ( x n ( sub1 m ))) It adds n ( where n = 12) to ( x n (sub1 m )) . What is the meaning of ( + n ( x n (sub1 m ))) It adds n ( where n 12) to the natural recursion. 66 Chapter 4 . (zero ? m ) No. What i s the value of the line ( ( zero ? m ) 0) 0. = What are the new arguments of ( x n m) n is 12. Are we finished yet? No. and m is 2 . What is the meaning of (+ n ( x n ( sub1 m ))) It adds n ( where n = 12) to ( x n (sub1 m )) .
always use 0 for the value of the terminating line. This technique works for all recursive functions. 12 3) Because 0 will not affect + . for multiplying by 1 does not change the value of a multiplication. for adding 0 does not change the value of an addition. where n is 12 and m is 3. You can use this approach to write functions as well as to argue their correctness. Numbers Games 67 . (x Again. not just those that use numbers. Notice that n has been +ed m times.Why not? Because we still have three +es to pick up. When building a value with x . that x is the conventional multiplication of nonnegative integers. using equations. always consider () for the value What is ( tup+ tup1 tup2) where tup1 is (3 6 9 1 1 4 ) and tup2 is (8 5 2 0 7) (11 11 11 11 11). What is the value of the original application? Argue. That is. always use 1 for the value of the terminating line. which is as we expected. n + O = n. = 12 + ( x 12 2) = 12 + 12 + ( x 12 1) = 12 + 12 + 12 + ( X 12 0) = 12 + 12 + 12 + 0. why is 0 the value for the terminal condition line in x The Fifth Commandment When building a value with + . Add 12 to 12 to 12 to 0 yielding 36. When building a value with of the terminating line. cons .
What is (tup+ tup1 tup2 ) where tup1 is (2 3) and tup2 is (4 6) (6 9). and if the second tup is empty or nonempty. because the tups must have the same length. 68 Cbapter 4 . building a tup of the answers. If you recur on one tup how many questions do you have to ask? Two. because ( null'? tup1 ) is true exactly when ( null'? tup2 ) is true. What does ( tup+ tup1 tup2 ) do? It adds the first number of tup1 to the first number of tup2. for tups of the same length. they are ( null? tup) and else. What is unusual about tup+ It looks at each element of two tups at the same time. it recurs on two tups. and so on. No. then it adds the second number of tup1 to the second number of tup2. or in other words. how many questions need to be asked about the tups? Four: if the first tup is empty or nonempty. Does this mean (and ( null'? tup1 ) ( null '? tup2 ) ) and else are the only questions we need to ask? Yes. Do you mean the questions (and ( null'? tup1 ) ( null'? tup2 ) ) ( null'? tup1 ) ( null'? tup2) and else Can the first tup be () at the same time as the second is other than () Yes. When recurring on two tups.
( + ( car tup1 ) ( car tup2 )) and ( tup+ ( cdr tup1 ) ( cdr tup2 ) ) . No. (7 13).Write the function tup+ (define tup+ (lambda ( tup1 tup2) (cond ((and ( null? tup1 ) ( null? tup2)) (quote ())) (else ( cons ( + ( car tup1 ) ( car tup2 )) ( tup+ ( cdr tup1 ) ( cdr tup2 ) ) ) ) ) ) ) What are the arguments of + in the last line? What are the arguments of cons in the last line? ( car tup1 ) and ( car tup2 ) . so now we are ready to consider the rest of both tups. But let 's see how it works. ( null? tup1 ) where tup1 is now (7) and tup2 is now (6) Numbers Games 69 . What is ( tup+ tup1 tup2) where tup1 is (3 7) and tup2 is (4 6) ( null? tup1 ) ( cons ( + ( car tup1 ) ( car tup2 )) ( tup+ ( cdr tup1 ) ( cdr tup2 ))) Why does the natural recursion include the cdr of both arguments? No. Because the typical element of the final value uses the car of both tups. cons 7 onto the natural recursion: ( tup+ ( cdr tup1 ) ( cdr tup2 ) ) .
since tup1 will become null before tup2. the cons of 7 onto the cons of 13 onto ( ) . What does the second new line look like? ( ( null ? tup2 ) tup1 ) . What is the value of the application? (7 13). That is. what must be the value? ( ) . since tup2 will become null before tup1. See The First Commandment: We did not ask all the necessary questions! But.( cons ( + ( car tup1 ) ( car tup2 )) ( tup+ ( cdr tup1 ) ( cdr tup2 ))) cons 13 onto the natural recursion. because ( null ? tup2) must be true. ( null ? tup1 ) Yes. 70 Chapter 4 . What problem arises when we want ( tup+ tup1 tup2 ) where tup1 is (3 7) and tup2 is ( 4 6 8 1 ) Can w e still write tup+ even i f the tups are not the same length? Yes! What new terminal condition line can we add to get the correct final value? Add ( ( null? tup1 ) tup2 ) . See The First Commandment: We did not ask all the necessary questions! What do we need to include in our function? We need to ask two more questions: ( null? tup1 ) and ( null? tup2 ) . Then . we would like the final value to be (7 13 8 1 ) . No answer. What is ( tup+ tup1 tup2) where tup1 is (3 7 8 1 ) and tup2 is (4 6) No answer.
Yes. How many questions do we have to ask about n and m Three: (zero ? n). Numbers Games 71 . because either ( null ? tup1 ) or ( null ? tup2 ) is true if either one of them does not contain at least one number. ) When do we recur? When we know neither number is equal to 0.( car tup1 ) ( car tup2 ) ) ( tup+ ( cdr tup 1 ) ( cdr tup2 ) ) ) ) ) ) ) Can you simplify it? (define tup+ (lambda ( tup1 tup2 ) (cond ( ( null? tup1 ) tup2 ) ( ( null? tup2 ) tup1 ) ( else ( cons ( + ( car tup1 ) ( car tup2 )) ( tup+ ( cdr tup1 ) ( cdr tup2 ) ) ) ) ) ) ) Does the order of the two terminal conditions matter? Is else the last question? No. What is (> 12 133) What is ( > 120 1 1 ) #t true. n and m. How do we recur? With (sub1 n) and ( sub1 m .Here is a definition of tup+ that works for any two tups: (define tup+ (lambda ( tup1 tup2 ) (cond ((and ( null? tup1 ) ( null? tup2 ) ) (quote ())) ((null? tup1 ) tup2 ) ( ( null? tup2 ) tup1 ) (else ( cons ( 11. ) and else. (zero ? m . #ffalse. O n how many numbers d o we have t o recur? Two.
Can you write the function > now using zero ? and sub1 How about (define > (lambda ( n m ) ( cond ((zero ? m ) #t ) ((zero ? n ) #f ) (else ( > (sub1 n ) (sub1 m )))))) Is the way we wrote ( > n m ) correct? No. What is the meaning of ( > (sub1 n ) (sub1 m )) Recur. so move to the next question. No. but with both arguments closer to zero by one. so move to the next question. so move to the next question. so move to the next question. but with both arguments reduced by one. (zero ? 2) No. What is the meaning of ( > (sub1 n ) (sub1 m )) Recur. but with both arguments reduced by one. (zero ? 1 ) No. Let n and m be 3. 72 Chapter 4 . so move to the next question. so move to the next question. try it for the case where n and same number. What is the meaning of ( > ( sub1 n ) (sub1 m )) Recur. m are the ( zero ? 3) (zero ? 3) No. (zero ? 1) No. (zero ? 2) No.
( < 8 3) #f. Switch the zero ? lines: (define > (lambda ( n m ) (cond ( ( zero ? n ) #f ) ((zero ? m ) #t ) (else ( > (sub1 n ) ( sub1 m )))))) What is ( < 4 6) #t . because 3 is not greater than 3. Try it out ! Yes. then try. (define < (lambda ( n m ) (cond ( ( zero ? m ) #f ) ((zero ? n ) #t ) (else ( < (sub1 n ) ( sub1 m )))))) Numbers Games 73 . (< 6 6) Now try to write < #f. Think about it. No.(zero ? 0) Is this correct? Does the order of the two terminal conditions matter? Does the order of the two terminal conditions matter? Does the order of the two previous answers matter? How can we change the function > to take care of this subtle problem? Yes. Think first . so the value of ( > n m ) is #t .
the natural recursion also looks strange. 125 . (define t1 (lambda ( n m ) (cond ((zero ? m ) 1 ) (else ( x n (t n ( sub1 m ))))))) 1 What is a good name for this function? L.Here is the definition of = (define = (lambda ( n m ) (cond ((zero ? m ) (zero ? n )) ((zero ? n ) #f ) (else (= ( sub1 n ) ( sub1 Rewrite = using < and > (define = (lambda ( n m ) (cond ( ( > n m ) #f ) ( ( < n m ) #f ) (else #t ) ) ) ) m )))))) Does this mean we have two different functions for testing equality of atoms? Yes. 8. 1.  n m ) m )))))) 74 Chapter 4 . = (t 1 1 ) (t 2 3) (t 5 3) Now write the function t Hint : See the The First and Fifth Commandments. S: This i s like expt . (define ? ? ? (lambda ( n m ) (cond ( ( < n m ) 0) (else ( add1 ( ? ? ? ( We have never seen this kind of definition before. they are for atoms that are numbers and eq ? for the others.
(define + 1 (lambda (n m) (cond ( ( < n m) O) (else ( add1 ( + (  n m) m)))))) 1 (values (truncate (/ n m} } } } S : This is like quot ient . When the function returns.What does the first question check? It determines whether the first argument is less than the second one. How do we get there? Easy. it is 3. So what does the function do? It counts how many times the second argument fits into the first one. And what happens in the second line? We recur with a first argument from which we subtract the second argument . we add 1 to the result . = Wouldn't a (ham and cheese on rye) Don't forget the be good right now? m ustard ! 75 Numbers Games . too: ( + 15 4) = 1 + ( + 11 4) 1 + ( 1 + ( + 7 4)) 1 + ( 1 + ( 1 + ( + 3 4) ) ) 1 + ( 1 + ( 1 + 0)). L : (defun quotient ( n m} What is (+ 15 4 ) Easy. And what do we call this? Division.
Now try to write the function length (define length (lambda ( lat) (cond ( ( null ? lat) 0) (else ( add1 ( length ( cdr lat))))))) What is (pick n lat) where n is 4 and lat is ( lasagna spaghetti ravioli macaroni meatball ) macaroni .What is the value of ( length lat) where lat is ( hotdogs with mustard sa uerkraut and pickles ) 6. 76 Chapter 4 . What is (pick 0 lat) where lat is ( a ) N o answer. Try to write the function pick (define pick (lambda ( n lat) (cond ((zero ? ( sub1 n)) ( car lat) ) (else (pick ( sub1 n) ( cdr lat)))))) What is ( rempick n lat) where n is 3 and lat is ( hotdogs with hot mustard ) ( hotdogs with m ustard ) . What is ( length lat) where lat is ( ham and cheese on rye ) 5.
1 L: numberp Is ( number? 76) true or false? True. and atom ?. null?. zero ?.Now try to write rempick (define rempick (lambda ( n lat) (cond ( (zero ? ( sub1 n ) ) ( cdr lat) ) (else ( cons ( car lat) ( rempick (sub1 n) ( cdr lat ) ) ) ) ) ) ) Is ( number?1 a) true or false where a is tomato False. is a primitive function. For example. cdr. where lat is (5 pears 6 prunes 9 dates) the value of ( nonums lat) is (pears pru nes dates) (define nonums (lambda ( lat) (cond ( ( null ? lat) (quote ( ) ) ) (else (cond ( ( number? ( car lat) ) ( nonums ( cdr lat ) ) ) (else ( cons ( car lat) ( nonums ( cdr lat ) ) ) ) ) ) ) ) ) Numbers Games 77 . eq ?. Now using number? write the function nonums which gives as a final value a lat obtained by removing all the numbers from the lat . cons . Can you write number? which is true if its argument is a numeric atom and false if it is anthing else? No: number?. like add1 . car. sub1 .
Now write the function occur which counts the number of times an atom a appears in a lat (define occur (lambda (a lat) (cond < (else (cond (define occur (lambda ( a lat) (cond ( ( null? lat) 0) (else (cond ( ( eq? ( car lat) a) ( add1 ( occur a ( cdr lat)))) (else ( occur a ( cdr lat)))))))) <  .) )))))) < __ 78 Chapter 4 . for eqan ? itself. of course. Remember to use = for numbers and eq? for all other atoms. (define eqan ? (lambda ( a1 a2 ) (cond ((and ( number? a1 ) ( number? a2 )) ( = a1 a2 ) ) ( (or ( number? a1 ) ( number? a2 )) #f ) (else ( eq? a1 a2 ) ) ) ) ) Can we assume that all functions written using eq ? can be generalized by replacing eq ? by eqan ? Yes. except . (define allnums (lambda ( lat) (cond ( ( null? lat) (quote ())) (else (cond ( ( number? ( car lat) ) ( cons ( car lat) ( allnums ( cdr lat) ) ) ) (else ( allnums ( cdr lat)))))))) Write the function eqan ? which is true if its two arguments ( a1 and a2 ) are the same atom .Now write allnums which extracts a tup from a lat using all the numbers in the lat .
making it a oneliner. . . . For example.e. By removing the ( cond .Write the function one ? where ( one ? n) is #t if n is 1 and #f ( i. where n is 3 and lat is (lemon meringue salty pie) the value of ( rempick n lat) is (lemon meringue pie) Use the function one ? in your answer. (define rempick (lambda ( n lat) (cond ( ( one ? n) ( cdr lat) ) (else ( cons ( car lat) ( rempick ( sub1 n) ( cdr lat ) ) ) ) ) ) ) Numbers Games 79 . false ) otherwise. ) clause: (define one ? (lambda (n) (= n 1 ) ) ) Now rewrite the function rempick that removes the nth atom from a lat. (define one ? (lambda (n) (cond ((zero ? n) #f ) (else (zero ? ( sub1 n ) ) ) ) ) ) or (define one ? (lambda (n) (cond (else ( = n 1 ) ) ) ) ) Guess how we can further simplify this function.
�' �· .
. t " ." ((coffee) ((tea)) (and (hick) ) } .What is ( rember* a l} where a is cup and l is ((coffee) cup ((tea) cup) (and (hick}} cup) "rember*" is pronounced "remberstar. Now write rember* t Here is the skeleton: (define rember* (lambda ( a l} (cond ( (    ( > . instead of just the cdr of the list .. *Oh My Gawd *: It 's Full of Stars 81 .> __  )))) (define rember* (lambda ( a l} (cond (( n ull? l} (quote ())) ( ( atom ? ( car l}} (cond ( ( eq? ( car l} a) ( rember* a ( cdr l))) ( else ( cons ( car l) ( rember* a ( cdr l))}))) ( else ( cons ( rember* a ( car l}} ( rember* a ( cdr l))})))) Using arguments from one of our previous examples. * " m akes u s think "oh my gawd." ( lat ? l} where l is (((tomato sauce)) ((bean) sauce) (and ((flying)) sauce)) #f. follow through this to see how it works. Notice that now we are recurring down the car of the list . What is ( rember* a l} where a is sauce and l is (((tomato sauce)) ((bean) sauce) (and ((flying)) sauce)) (((tomato)) ((bean)) (and ((flying) ) ) ) .
Is ( car l) an atom where l is ( ( (tomato sa uce) ) ( ( bean) sauce) (and ( (flyi ng) ) sauce) ) No. What is ( insertR * new old l) where new is roast old is chuck and l is ( ( how much (wood ) ) cou ld ((a (wood ) chuck) ) ( ( (chuck) ) ) ( i f ( a ) ((wood chuck) ) ) could chuck wood ) ( (how much (wood) ) cou ld ((a (wood) chuck roast) ) ( ( (chuck roast))) (if (a) ((wood chuck roast))) cou ld chuck roast wood ) . ( define insertR * (lambda ( new old l) ( c o nd ( ( ( ) ) )))) ( defi ne insertR * (lambda ( new old l) ( c o nd ( ( null? l) (quote ())) ( ( atom ? ( car l)) ( c o nd (( eq ? ( car l) old ) ( cons old ( cons new ( insertR * new old ( cdr l))))) (else ( cons ( car l) ( insertR * new old ( cdr l)))))) (else ( cons ( insertR * new old ( car l)) ( insertR * new old ( cdr l))))))) How are insertR * and rember* similar? Each function asks three questions. 82 Chapter 5 . Now write the function insertR * which inserts the atom new to the right of old regardless of where old occurs.
The F irst Commandment (final version) When recurring on a list of atoms. as well as with the cdr. l. ask two questions about it: ( null? lat) and else. n . and else. When recurring on a list of Sexpressions. When recurring on a number. ( atom ? ( car l) ) . How are insertR * and rember* similar? How are all *functions similar? They all ask three questions and recur with the car as well as with the cdr. It recurs with the car when it finds out that the car is a list . They both recur with the car. lat . ask three question about it: ( null? l ) . How are rember* and multirember different? The function multirember does not recur with the car. whenever the car is a list. *Ob My Gawd *: It 's Full of Stars 83 . or . ask two questions about it: (zero ? n) and else.an atom consed onto a list . Why? Because all *functions work on lists that are either . The function rember* recurs with the car as well as with the cdr. . whenever the car is a list .a list consed onto a list .empty. How are insertR * and rember* similar? Each function recurs on the car of its argument when it finds out that the argument 's car is a list .
The Fourt h Commandment
(final version)
Always change at least one argument while recurring. When recurring on a list of atoms, lat, use ( cdr lat ) . When recurring on a number, n , use (sub1 n) . And when recur ring on a list of Sexpressions, l , use ( car l) and ( cdr l) if neither ( null ? l) nor ( atom ? ( car l)) are true. It must be changed to be closer to termination. The chang ing argument must be tested in the termination condition: when using cdr , test termination with null ? and when using sub1 , test termination with zero ?.
( occursomething a l) where a i s ba nana and l is ((banana) (split ( ( ( ( banana ice) ) ) (crea m ( banana)) sherbet)) ( banana) (bread) (banana brandy) )
5.
What is a better name for occursomething
occur* .
84
Chapter
5
Write occur*
(define occur* (lambda (a l) (cond
<  ___ ) <  ___ ) (  __ ) ) ) )
(define occur* (lambda (a l) (cond ( ( null? l) 0) ( ( atom ? ( car l)) (cond ( ( eq? ( car l) a) ( add1 ( occur * a ( cdr l)))) (else ( occur* a ( cdr l))))) (else ( + ( occur* a ( car l)) ( occur* a ( cdr l ) ) ) ) ) ) )
( subst * new old l) where new is orange old is banana and l is ((banana) (split ((((banana ice) ) ) (cream (banana ) ) sherbet)) (banana) (bread) (banana brandy) )
((orange) (split ( ( ( (orange ice) ) ) (crea m (ora nge)) sherbet)) (orange) (bread) (orange brandy) ) .
Write subst *
( define subst*
(lambda ( new old l) ( cond ( ( null ? l) (quote ( ))) ( ( atom ? ( car l)) ( cond (( eq ? ( car l) old ) ( cons new ( subst * new old ( cdr l)))) ( else ( cons ( car l) (subst * new old ( cdr l)))))) ( else ( cons ( subst* new old ( car l)) ( subst* new old ( cdr l ) ) ) ) ) ) )
(define subst * (lambda ( new old l) ( cond
<  ___ ) <  ___ ) <  __ ) ) ) )
*Oh My Gawd*: It 's Full of Stars
85
What is ( insertL * new old l) where new is peeker old is chuck and l is ( (how much (wood ) ) could ( (a (wood ) chuck)) (( (chuck) )) (if (a) ( (wood chuck ) ) ) cou ld chuck wood)
( (how m uch (wood ) ) cou ld ((a (wood) peeker chuck)) ( ( (peeker chuck))) (if (a) ((wood peeker chuck) ) ) cou ld peeker chuck wood) .
Write insertL *
(define insertL * (lambda ( new old l) ( c ond ( ( (
__ _ 

___ __
) ) ))))
( define insertL * (lambda ( new old l ) ( c ond ( ( null? l ) (quote () ) ) (( atom ? ( car l) ) ( c ond ( ( eq? ( car l) old ) ( cons new ( cons old ( insertL * new old ( cdr l ))))) (else ( cons ( car l ) ( insertL * new old ( cdr l )))))) (else ( cons ( insertL * new old ( car l )) ( insertL * new old ( cdr l )))))))
a l) where a is chi ps and l is ( (potato) (chips ( (with) fish ) (chips) ) )
( member*
#t because the atom chips appears i n the list l.
,
86
Chapter
5
Write member* ( define member* (lambda ( a l) (cond ( ( (

___
_ __
__

) ) ))))
( define member* (lambda (a l) (cond ( ( null ? l) #f ) ( ( atom ? ( car l) ) (or ( eq ? ( car l) a) ( member* a ( cdr l) ) ) ) (else (or ( member* a ( car l)) ( member* a ( cdr l ) ) ) ) ) ) )
What i s ( member* a l) where a is chips and l is ( (potato) (chips ( (with) fish) (chips) ) ) Which chips did i t find?
#t .
( ( potato) (chips ( (with) fish ) (chi ps) ) ) . potato.
What is ( leftmost l) where l is ((potato) (chips ( (with) fish) (chips) ) )
What i s ( leftmost l) where l is (((hot) (tuna (and ) ) ) cheese) What is ( leftmost l) where l is (((() four)) 17 (seventeen) ) What i s ( leftmos t (quote ( ) ) )
hot.
No answer.
No answer.
C an you describe what leftmost does?
Here is our description : "The function leftmost finds the leftmost atom in a nonempty list of Sexpressions that does not contain the empty list."
*Oh My Gawd *: It 's Fun of Stars
87
it only needs to ask two questions. What is (and ( atom ? ( car l)) ( eq ? ( car l) x ) ) where x is pizza and l is (mozzarella pizza) Why is it false? Since (and . No. making its value true. . ) asks questions one at a time until it finds one that is true. but it only recurs on the car.. Then ( or . . . #f. . 88 Chapter 5 . ) does? ( or . which is true. . ) is false. Does leftmost need to ask questions about all three possible cases? Now see if you can write the function leftmost (define leftmost (lambda (l) ( cond (define leftmost (lambda (l) ( co nd ( ( atom ? ( car l)) ( car l)) (else ( leftmost ( car l)))))) < <  __  ) )))) D o you remember what ( or . . which is false.Is leftmost a *function? It works on lists of Sexpressions. . the value of ( or . . ) asks ( atom ? ( car l)). hence it is #f. it then asks ( eq ? ( car l) x ) . If it cannot find a true argument . ) stops.. We agreed that leftmost works on nonempty lists that don 't contain empty lists.
" True. If none of the expressions are false. ) stops if the first argument has the value #f. . ) does. . . True or false: it is possible that one of the arguments of (and . Here's one: x is pizza and l is ( pizza ( tastes good ) ) . Put in your own words what (and . . . ) is true. . . . and ( or . expressions: (and tt {3) (or tt {3) = 1 (cond (tt {3) (else #f)) ) and = (cond ( tt #t) (else {3)) ( eqlist ? l1 l2 ) where l1 is ( strawberry ice crea m ) and l2 is ( strawberry ice cream ) #t . . . ) stops with false. Because of this property. . . . . ) stops if the first argument has the value #t . . (and . however. . ) asks ( atom ? ( car l ) ) . . though both (and . ) can be deft ned as functions in terms of (cond . Since (and . ) also has the property of not considering all of its arguments. so it is #f. . ) nor (or . . . . neither (and . and ( car l) is not an atom . . . . . . ) . Then (and . ) is not considered? 1 ( cond . . .What is (and ( atom ? ( car l)) ( eq? ( car l) x)) where x is pizza and l is (( mozzarella m ushroom ) pizza ) Why is it false? #f. . because (and . ) asks questions one at a time until it finds one whose value is false. ) can be expressed as abbreviations of ( cond . . ) and ( or . . . We put it in our words: "(and . *Oh My Gawd*: It 's Full of Stars 89 . Give an example for x and l where (and ( atom ? ( car l)) ( eq? ( car l) x)) is true. ) and (or .
an atom consed onto a list .empty.( eqlist ? l1 l2 ) where l1 is (strawberry ice crea m ) and l2 is (strawberry crea m ice) ( eqlist ? l1 l2 ) where l1 is (banana ( (split) ) ) and l2 is ( ( banana) (split)) ( eqlist? l1 l2 ) where l1 is (beef ( (sa usage)) (and (soda))) and l2 is (beef ( (sala m i ) ) (and (soda))) ( eqlist ? l1 l2 ) where l1 is (beef ( (sausage)) (and (soda))) and l2 is (beef ( (sa usage) ) (and (sod a ) ) ) What i s eqlist ? #f. It is a function that determines if two lists are equal. For example.a list consed onto a list . That 's better. Nine. or ." 90 Chapter 5 . How many questions will eqlist ? have to ask about its arguments? Can you explain why there are nine questions? Here are our words: "Each argument may be either . the second argument could be the empty list or have an atom or a list in the car position. . #f. but almost #t . #t . #f. at the same time as the first argument may be the empty list .
the second argument is neither the empty list nor a list with an atom as the first element . we know that when the first argument is empty. True or false: if the first argument is () eqlist ? responds with #t in only one case. l2 must also be the empty list. the second argument must be a list whose first element is also a list. True. And why is the third question ( null? l1 ) At that point . *Oh My Gawd *: It 's Full of Stars 91 . If ( null? l1 ) is true now. Otherwise the first question would have been true. For ( eqlist ? (quote ( ) ) l2 ) to be true.Write eqlist ? using eqan ? (define eqlist ? (lambda ( l1 l2 ) ( c ond ((and ( null? l1 ) ( null? l2) ) #t ) ((and ( null? l1 ) ( atom ? ( car l2 ) ) ) #f ) ( ( null? l1 ) #f ) ((and ( atom ? ( car l1 ) ) ( null? l2 ) ) #f ) ((and ( atom ? ( car l1 ) ) ( atom ? ( car l2 ) ) ) (and ( eqan ? ( car l1 ) ( car l2 ) ) ( eqlist ? ( cdr l 1 ) ( cdr l2 ) ) ) ) ( ( atom ? ( car l1 ) ) #f ) ( ( null? l2 ) #f ) ( ( atom ? ( car l2 ) ) #f ) (else (and ( eqlist ? ( car l1 ) ( car l2 ) ) ( eqlist ? ( cdr l 1 ) ( cdr l2 ) ) ) ) ) ) ) Is it okay to ask ( atom ? ( car l2 ) ) in the second question? Yes. because we know that the second list cannot be empty.
Does this mean that the questions (and ( null? 11 ) ( null? l2 ) ) and ( or ( null? 11 ) ( null? 12 )) suffice to determine the answer in the first three cases? Rewrite eqlist ?
Yes. If the first question is true, eqlist ? responds with #t ; otherwise, the answer is #f.
( define eqlist ? (lambda ( l1 12 ) ( cond ((and ( null? 11 ) ( null? 12) ) #t ) (( or ( null? 11 ) ( null? 12)) #f ) ((and ( atom ? ( car l1 )) ( atom ? ( car 12) ) ) (and ( eqan ? ( car 11 ) ( car 12 )) ( eqlist ? ( cdr 11 ) ( cdr 12 )))) (( or ( atom ? ( car l1 ) ) ( atom ? ( car 12 ))) #f ) (else (and ( eqlist ? ( car 11 ) ( car 12) ) ( eqlist? ( cdr 11 ) ( cdr l2 )))))))
What i s an Sexpression?
An Sexpression is either an atom or a (possibly empty) list of Sexpressions. Four. The first argument may be an atom or a list of Sexpressions at the same time as the second argument may be an atom or a list of Sexpresssions.
How many questions does equal? ask to determine whether two Sexpressions are the same?
Write equal?
(define equal? (lambda (s1 s2 ) ( cond ((and ( atom ? s1 ) ( atom ? s2)) ( eqan ? s1 s2 )) ( ( atom ? s1 ) #f ) (( atom? s2 ) #f ) (else ( eqlist? s1 s2 )))))
92
Chapter 5
Why is the second question ( atom ? s1 )
If it is true, we know that the first argument is an atom and the second argument is a list .
And why is the third question ( atom ? s2)
By the time we ask the third question we know that the first argument is not an atom. So all we need to know in order to distinguish between the two remaining cases is whether or not the second argument is an atom . The first argument must be a list.
Can we summarize the second question and the third question as ( or ( atom ? s1 ) ( atom ? s2 ) )
Yes, we can!
Simplify equal?
(define equal ? (lambda (s1 s2 ) ( co nd ((and ( atom ? s1 ) ( atom ? s2 ) ) ( eqan ? s1 s2 ) ) ( ( or ( atom ? s1 ) ( atom ? s2 ) ) #f ) (else ( eqlist ? s1 s2 ) ) ) ) )
Does equal? ask enough questions?
Yes. The questions cover all four possible cases.
Now, rewrite eqlist ? using equal?
(define eqlist ? (lambda ( l 1 l2 ) ( co nd ((and ( null? l1 ) ( null? l2 ) ) #t ) ( ( or ( null? l1 ) ( null? l2 ) ) #f ) (else (and ( equal? ( car l1 ) ( car l2 ) ) ( eqlist ? ( cdr l 1 ) ( cdr l2 ) ) ) ) ) ) )
*Ob My Gawd*: It 's Full of Stars
93
T he S ixt h Commandment
Simplify only after the function is correct.
Here is rember after we replace lat by a list l of Sexpressions and a by any Sexpression.
Obviously!
(define rember (lambda ( s l) (cond ( ( null? l) (quote ( ) ) ) ( ( atom ? ( car l)) (cond ( ( equal? ( car l) s) ( cdr l)) (else ( cons ( car l) ( rember s ( cdr l)))))) (else (cond ( ( equal ? ( car l) s) ( cdr l)) (else ( cons ( car l) ( rember s ( cdr l ) ) ) ) ) ) ) ) )
Can we simplify it?
(define rember (lambda (s l) (cond ( ( null ? l) (quote ())) (else (cond ( ( equal? ( car l) s) ( cdr l)) (else ( cons ( car l) ( rember s ( cdr l)))))))))
And how does that differ?
The function rember now removes the first matching Sexpression s in l, instead of the first matching atom a in lat.
Is rember a "star" function now? Why not ?
No.
Because rember recurs with the cdr of l only.
Can rember be further simplified?
Yes, the inner ( cond . . . ) asks questions that the outer ( cond . . . ) could ask!
94
Chapter
5
Do it !
(define rember (lambda ( s l) (cond ( ( null? l) (quote ( ) ) ) ( ( equal? ( car l) s ) ( cdr l)) (else ( cons ( car l) ( rember s ( cdr l ) ) ) ) ) ) )
Does this new definition look simpler?
Yes, i t does!
And does it work just as well?
Yes, because we knew that all the cases and all the recursions were right before we simplified.
Simplify insertL *
We can't. Before we can ask ( eq 'l ( car l) old) we need to know that ( car l) is an atom .
When functions are correct and welldesigned, we can think about them easily.
And that saved us this time from getting it wrong.
Can all functions that use eq? and = be generalized by replacing eq 'l and = by the function equal?
Not quite; this won't work for eqan ?, but will work for all others. In fact , disregarding the trivial example of eqan 'l, that is exactly what we shall assume.
*Oh My Gawd *: It 's Full of Stars
95
(])EO �dl�l@) .
What is an arithmetic expression in your words? In ours: "For the purpose of this chapter. Is 1 + 3 an arithmetic expression? Yes! Is 1 +3 x 4 an arithmetic expression? Definitely. Are you almost ready for one? And. What does (quote x ) stand for? The atom x.. what about 3 t y + 5 Yes. an arithmetic expression is either an atom (including numbers). Is cookie an arithmetic expression? Yes. Shadows 97 . or t." What is (quote a) a. not the operation x. That 's the same question again.Is 1 an arithmetic expression? Yes. x . What is (quote +) The atom + . or two arithmetic expressions combined by + . of course. And the answer is still true. not the operation 11. Is ( eqP (quote a ) 11) true or false where 11 is a Is ( eqP x 11) true or false where x is a and 11 is a True. Is 3 an arithmetic expression? Yes .
( n + 3) is an Sexpression. What is numbered ? It is a function that determines whether a representation of an arithmetic expression contains only numbers besides the + . 2. Our definition of arithmetic expression does not mention parentheses. How do you represent 3 +4 5 (3 + (4 X 5)). True or false: ( numbered ? y) where y is (3 + (4 t 5)) True. Could we think of ( n + 3) expression? as an arithmetic Yes. because sausage is not a number. 98 Chapter 6 .Is ( n + 3) an arithmetic expression? Not really. True or false: ( numbered ? x ) where x is 1 x True. Because 1. since there are parentheses around n + 3. What would you call ( n + 3) Why is ( n + 3) a good representation? We call it a representation for n + 3. if we keep in mind that the parentheses are not really there. True or false: ( numbered ? z ) where z is (2 x sa usage) False. x . and t. It structurally resembles n + 3. It can therefore serve as an argument for a function.
Shadows 99 . What is ( eq? ( car ( cdr aexp)) (quote + ) ) I t i s the second question. And you must know the fourth one. instead of two. What is the first question? ( atom ? aexp ) . ( eq? ( car ( cdr aexp)) (quote t)). questions about arithmetic expressions? After all. not as a list itself. arithmetic expressions like (1 + 3) are lats. an arithmetic expression is either a number. o f course. or two arithmetic expressions combined by + . And. or t. Because we consider (1 + 3) as a representation of an arithmetic expression in list form . x .Now can you write a skeleton for numbered ? (define numbered ? (lambda ( aexp ) (cond ( (   ( ( _ __   __  ) ) ) )))) is a good guess. C an you guess the third one? ( eq ? ( car ( cdr aexp)) (quote x ) ) is perfect . Why do we ask four. Should we ask another question about aexp No! So we could replace the previous question by else.
Now you can almost write numbered ? Here is our proposal: (define numbered ? (lambda ( aexp) (cond ( ( atom ? aexp) ( number? aexp)) ( ( eq ? ( car ( cdr aexp)) (quote +)) .) ( ( eq? ( car ( cdr aexp)) (quote x )) . . In which position is the first subexpression? It is the car of aexp. . In which position is the second subexpression? It is the car of the cdr of the cdr of aexp. .)))) Why do we ask ( number? aexp) when we know that aexp is an atom? Because we want t o know i f all arithmetic expressions that are atoms are numbers.) ( ( eq? ( car ( cdr aexp)) (quote t) ) . What is the second answer? (and ( numbered ? ( car aexp)) ( numbered ? ( car ( cdr ( cdr aexp) )))) 100 Chapter 6 . . Both must b e true. What do we need to know if the aexp consists of two arithmetic expressions combined by + We need to find out whether the two subexpressions are numbered. So what do we need to ask? ( numbered ? ( car aexp)) and ( numbered ? ( car ( cdr ( cdr aexp) ) ) ) . . .
Shadows 101 . (define numbered ? (lambda ( aexp) (cond ( ( atom ? aexp) ( number? aexp)) ( ( eq ? ( car ( cdr aexp)) (quote + ) ) (and ( numbered ? ( car aexp)) ( numbered ? ( car ( cdr ( cdr aexp ) ) ) ) ) ) ( ( eq? ( car ( cdr aexp)) (quote x )) (and ( numbered ? ( car aexp)) ( numbered ? ( car ( cdr ( cdr aexp ) ) ) ) ) ) ( ( eq ? ( car ( cdr aexp)) (quote t ) ) (and ( numbered ? ( car aexp)) ( numbered ? ( car ( cdr ( cdr aexp) ) ) ) ) ) ) ) ) Since aexp was already understood to be an arithmetic expression. could we have written numbered? in a simpler way? Yes: (define numbered ? (lambda ( aexp) (cond ( ( atom ? aexp) ( number? aexp)) (else (and ( numbered ? ( car aexp)) ( numbered ? ( car ( cdr ( cdr aexp) ) ) ) ) ) ) ) ) Why can we simplify? Because we know we've got the function right . (value x) where x is (1 + 3) 4.Try numbered ? again. What is ( value u) where u is 13 13.
( value nexp) returns what we think is the natural value of a numbered arithmetic expression. .) ( ( eq? ( car ( cdr nexp)) (quote x )) . ) ( ( eq? ( car ( cdr nexp)) (quote +)) . We hope. . . . No answer. . ) ) ) ) What is the natural value of an arithmetic expression that is a number? I t i s just that number. . Now. How many questions does value ask about nexp Four. we could just add up the two values. . 102 Chapter 6 . Can you think of a way to get the value of the two subexpressions in ( 1 + (3 x 4 ) ) Of course. and applying value to (3 x 4) . What is the natural value of an arithmetic expression that consists of two arithmetic expressions combined by + If we had the natural value of the two subexpressions. by applying value to 1 .( value y) where y is (1 + (3 t 4) ) ( value z ) where z is cookie 82.) (else . . let 's attempt to write value (define value (lambda ( nexp) (cond ( ( atom ? nexp) .
Shadows 103 . (define value (lambda ( nexp) (cond ( ( atom ? nexp) nexp) ( ( eq ? ( car ( cdr nexp)) (quote +)) ( + ( value ( car nexp)) ( value ( car ( cdr ( cdr nexp)))))) ( ( eq ? ( car ( cdr nexp)) (quote x ) ) ( x ( value ( car nexp ) ) ( value ( car ( cdr ( cdr nexp)))))) (else ( t ( value ( car nexp)) ( value ( car ( cdr ( cdr nexp) ) ) ) ) )))) Can you think of a different representation of arithmetic expressions? There are several of them. Could (3 4 +) represent 3 + 4 Could ( + 3 4) Yes. Or (plus 3 4 ) Yes.And in general? By recurring with value on the subexpressions. Give value another try. The S event h Commandment Recur on the subparts that are of the same nature: • On the sublists of a list. • On the subexpressions of an arithmetic expression. Yes.
What about (define value (lambda ( nexp) (cond ( ( atom ? nexp) nexp) ( ( eq ? ( car nexp) (quote +)) ( 11. It's wrong.Is (+ ( x 3 6) (t 8 2)) a representation of an arithmetic expression? Yes. 104 Chapter 6 . (+ 1 3) . Let 's try an example.( value ( cdr nexp)) ( value ( cdr ( cdr nexp))))) ( ( eq ? ( car nexp) (quote x )) ( x ( value ( cdr nexp)) ( value ( cdr ( cdr nexp))))) (else (t ( value ( cdr nexp )) ( value ( cdr ( cdr nexp)))))))) You guessed it. ( eq? ( car nexp) (quote + ) ) where nexp is ( + 1 3) Yes.a list of the atom t followed by two arithmetic expressions.a number . And now recur. ( atom ? nexp) where nexp is ( + 1 3 ) No.a list of the atom + followed by two arithmetic expressions. .a list of the atom x followed by two arithmetic expressions. or . Try to write the function value for a new kind of arithmetic expression that is either: . What is ( cdr nexp) where nexp is (+ 1 3) Yes. ( 1 3) .
not all lists are representations of arithmetic expressions. (define 1stsubexp (lambda ( aexp) (cond (else ( car ( cdr aexp ) ) ) ) ) ) Why do we ask else Because the first question i s also the last question . ) if we don't need to ask questions? Yes. the cdr of the cdr is (3) . We have to recur on subexpressions. Again. . What do we mean if we say the car of the cdr of nexp The first subexpression of the representation of an arithmetic expression. . But remember. we were thinking of the list ( + 1 3) instead of the representation of an arithmetic expression. remember oneliners from chapter 4. Taking the car of the cdr of the cdr gets us back on the right track. How can we get the first subexpression of a representation of an arithmetic expression? By taking the car of the cdr. (1 3) is not a subpart that is a representation of an arithmetic expression! We obviously recurred on a list . No. we violated The Seventh Commandment .(1 3) is not our representation of an arithmetic expression. Is ( cdr ( cdr nexp)) an arithmetic expression where nexp is ( + 1 3) No. Can we get by without ( cond . and (3) is not an arithmetic expression . (define 1stsubexp (lambda ( aexp) ( car ( cdr aexp)))) Shadows 105 . Let 's write a function 1stsubexp for arithmetic expressions.
let 's replace ( car nexp) by ( operator nexp) (define operator (lambda ( aexp) ( car aexp))) Now write value again.Write 2ndsubexp for arithmetic expressions. by changing 1stsubexp and operator. Do it ! (define 1stsubexp (lambda ( aexp ) ( car aexp))) ( define operator (lambda ( aexp ) ( car ( cdr aexp)))) 106 Chapter 6 . (define value (lambda ( nexp) (cond ( ( atom ? nexp) nexp) ( ( eq ? ( operator nexp) (quote +)) ( + ( value ( 1 stsubexp nexp)) ( value ( 2ndsubexp nexp) ))) ( ( eq ? ( operator nexp) (quote x )) ( x ( value ( 1 stsubexp nexp)) ( value ( 2ndsubexp nexp) ))) (else ( t ( value ( 1stsubexp nexp)) ( value ( 2ndsubexp nexp) )))))) Can we use this value function for the first representation of arithmetic expressions in this chapter? Yes . (define 2ndsubexp (lambda ( aexp) ( car ( cdr ( cdr aexp))))) Finally.
How shall we represent zero now? () is our choice. Shadows 107 . What else could we have used? ( () () () ( ) ) would have served j ust as well. Let's try another representation for numbers. we just did not tell you that they were representations. For what entities have we used representations? Truthvalues! Numbers! Numbers are representations? Yes. because we used help functions to hide the representation . How is one represented? (()). We chose that symbol because we are accustomed to arabic representations. How is two represented? (() ()). The Eight h Commandment Use help functions to abstract from representations. Have we seen representations before? Yes. add1 .Wasn't this easy? Yes . For example 4 stands for the concept four. What about ( ( ( ( ( ) ) ) ) ) ? How about (I V)? Do you remember how many primitives we need for numbers? Four: number?. zero ?. and sub1 .
Recall The Law of Cdr. but only slightly. It changed. What is (zub1 n) where n is ( ) No answer.Got it? What 's three? Three is ( () () () ) . 108 Chapter 6 . (define sero ? (lambda (n) ( null? n))) Can you write a function that is like add1 (define edd1 (lambda (n) ( cons (quote ()) n))) What about sub1 (define zub1 (lambda (n) ( cdr n))) Is this correct? Let 's see. (define + (lambda ( n m ) (cond ( ( sero ? m ) n) (else ( edd1 ( + n (zub1 m))))))) Has the definition of + changed? Yes and no. Rewrite + using this representation. Write a function to test for zero. . but that 's fine.
((()) ( ( ) ( ) ) ( ( ) ( ) ( ) ) ) . You must beware of shadows. Shadows 109 . .Recall lat ? Easy: (define lat ? (lambda (l) (cond ( ( null? l) #t ) ( ( atom ? ( car l)) ( lat? ( cdr l))) (else #f ) ) ) ) But why did you ask? Do you remember what the value of ( lat ? ls ) is where ls is (1 2 3) What is ( 1 2 3) with our new numbers? #t of course. What is ( lat? ls ) where ls is ((( )) (() ( )) (() ( )())) Is that bad? It is very false.
� lUhi]� � f!� �  " ��� .
because no atom appears more than once. because no atom appears more than once.Is this a set? (apple peaches apple plum) No. How about ( set ? lat) where lat is ( ) #t . Friends and Relations 111 . Were you surprised to see the function member? appear in the definition of set ? You should not be. True or false: ( set ? lat) where lat is (a pples peaches pears plu ms) #t . and now we can use it whenever we want . Try t o write set ? (define set ? (lambda ( lat) (cond ( ( null? lat) #t ) (else (cond ( ( member? ( car lat) ( cdr lat) ) #f ) (else ( set ? ( cdr lat ) ) ) ) ) ) ) ) Simplify IJet ? (define set ? (lambda ( lat) (cond ( ( null ? lat) #t ) ( ( member? ( car lat) ( cdr lat) ) #f ) (else (set? ( cdr lat ) ) ) ) ) ) Does this work for the example (apple 3 pear 4 9 apple 3 4} Yes. since member? i s now written using equal ? instead of eq ?. since a pple appears more than once. because we have written member? already.
Using the previous definition .What is ( makeset lat) where lat is (apple peach pear peach plum a pple lemon peach) (apple peach pear p l u m lemon ) . Try to write makeset using multirember (define makeset (lambda ( lat) (cond ( ( null ? lat) (quote ())) (else ( cons ( car lat) ( makeset ( multirember ( car lat) ( cdr lat)))))))) What is the result of ( makeset lat) using this second definition where lat is (apple peach pear peach plum apple lemon peach) (apple peach pear plum lemon ) . what is the result of ( makeset lat) where lat is (apple peach pear peach plum apple lemon peach) (pear plum apple lemon peach) . 112 Chapter 7 . Try to write makeset using member ? (define makeset (lambda ( lat) (cond ( ( null? lat) (quote ())) ( ( member? ( car lat) ( cdr lat) ) ( makeset ( cdr lat))) (else ( cons ( car lat) ( makeset ( cdr lat))))))) Are you surprised to see how short this is? We hope so. But don't be afraid: it 's right.
Here are our words: "The function makeset remembers to cons the first atom in the lat onto the result of the natural recursion. since multirember is now written using equal? instead of eq ?.Describe in your own words how the second definition of makeset works. because each atom in set1 is also in set2." Does the second makeset work for the example (apple 3 pear 4 9 apple 3 4) Yes. What is (subset? set1 set2 ) where set1 is (4 pounds of horseradish) and set2 is (four pounds chicken and 5 ou nces horseradish) #f. Write subset? (define subset ? (lambda (set1 set2 ) (cond ( ( null? set1 ) #t ) (else (cond ( ( member? ( car set1 ) set2 ) ( subset? ( cdr set1 ) set2 ) ) (else #f ) ) ) ) ) ) Friends and Relations 1 13 . after removing all occurrences of the first atom from the rest of the lat . What is (subset ? set1 set2 ) where set1 is (5 chicken wings) and set2 is (5 hamburgers 2 pieces fried chicken and light duckling wings) #t .
. ) (define subset ? (lambda (set1 set2 ) (cond ( ( null? set1 ) #t ) (else (and ( member? ( car set1 ) set2 ) ( subset ? ( cdr set1 ) set2)))))) What is ( eqset ? set1 set2 ) where set1 is (6 large chickens with wings) and set2 is (6 chickens with large wings) #t . Write eqset ? (define eqset ? (lambda ( set1 set2 ) (cond ( ( subset ? set1 set2 ) ( subset? set2 set1 ) ) (else #f ) ) ) ) Can you write eqset ? with only one condline? (define eqset ? (lambda ( set1 set2 ) (cond (else (and ( subset? set1 set2 ) ( subset? set2 set1 )))))) 1 14 Chapter 7 . .Can you write a shorter version of subset ? (define subset? (lambda ( set1 set2 ) (cond ( ( null ? set1 ) #t ) ( ( member? ( car set1 ) set2 } (subset ? ( cdr set1 ) set2 ) ) (else #f ) ) ) ) Try to write subset ? with (and .
(define eqset ? (lambda ( set1 set2 ) (and ( subset ? set1 set2 ) (subset ? set2 set1 ) ) ) ) What is ( intersect? set1 set2 ) where set1 is (stewed tomatoes and macaroni) and set2 is ( macaroni and cheese) Define the function intersect? #t . . . ) (define intersect ? (lambda ( set1 set2 ) ( cond ( ( null ? set1 ) #f ) (else ( or ( member? ( car set1 ) set2 ) ( intersect? ( cdr set1 ) set2 ) ) ) ) ) ) Compare subset? and intersect ?.Write the oneliner. (define intersect? (lambda ( set1 set2 ) ( cond ( ( null ? set1 ) #f ) (else ( cond ( ( member? ( car set1 ) set2 ) #t ) (else ( intersect ? ( cdr set1 ) set2 ) ) ) ) ) ) ) Write the shorter version. (define intersect? (lambda ( set1 set2 ) ( cond ( ( null? set1 ) #f ) ( ( member? ( car set1 ) set2 ) #t ) (else ( intersect? ( cdr set1 ) set2 ) ) ) ) ) Try writing intersect? with ( or . Friends and Relations 115 . because at least one atom in set1 is in set2 .
set1 and is is set2 Now you can write the short version of intersect (define intersect (lambda (set1 set2 ) (cond (( null? set1 ) (quote ())) (( member? ( car set1 ) set2 ) ( cons ( car set1 ) ( intersect ( cdr set1 ) set2))) (else (intersect ( cdr set1 ) set2))))) What is where ( union set1 set2 ) (stewed tomatoes and macaroni casserole) (macaroni and cheese) (stewed tomatoes casserole macaroni and cheese) set1 and is set2 is Write union (define union (lambda (set1 set2) (cond (( null? set1 ) set2 ) ( ( member? ( car set1 ) set2 ) ( union ( cdr set1 ) set2)) (else ( cons ( car set1 ) ( union ( cdr set1 ) set2)))))) 1 16 Chapter 7 .What is where ( intersect set1 set2 ) (stewed tomatoes and macaroni) (macaroni and cheese) (and macaroni).
Now. because i t i s a list with only two atoms. What i s ( intersectall lset) where lset is ( ( a b c) ( c a d e) ( e f g h a b)) (a) .What is this function? (define xxx (lambda ( set1 set2 ) (cond ( ( null? set1 ) (quote ( ) ) ) ( ( member? ( car set1 ) set2 ) ( xxx ( cdr set1 ) set2 ) ) (else ( cons ( car set1 ) ( xxx ( cdr set1 ) set2 ) ) ) ) ) ) In our words: "It is a function that returns all the atoms in set1 that are not in set2. Friends and Relations 117 . What is ( intersectall lset) where lset is ( ( 6 pears and) (3 peaches and 6 peppers) (8 pears and 6 plu ms) (and 6 pru nes with some apples) ) (6 a nd ) . (define intersectall (lambda ( lset) (cond ( ( null? ( cdr lset)) ( car lset)) (else ( intersect ( car lset) ( intersectall ( cdr lset ) ) ) ) ) ) ) Is this a pair?1 ( pear pear ) Yes. using whatever help functions you need. write intersectall assuming that the list of sets is nonempty. 1 A pair in Scheme (or Lisp) is a different but related object. xxx is the ( set ) difference function." That is.
By taking the car of the cdr of the pair. Define apair? (define apair? (lambda (x) (cond ( ( ato m ? x) #f ) ( ( n ull ? x) #f ) ( ( null ? ( cdr x)) #f ) ( ( n ull ? ( cdr ( cdr x))) #t ) (else #f ) ) ) ) How can you refer to the first Sexpression of a pair? How can you refer to the second Sexpression of a pair? By taking the car of the pair. there aren't any. That is. Did you notice the differences between the last two answers? 1 18 Chapter 7 . because it is a list with only two Sexpressions.Is this a pair? (3 7) Is this a pair? ((2) ( pair) ) Yes. Yes. How can you build a pair with two atoms? You cons the first one onto the cons of the second one onto ( ) That is. ( cons x1 ( cons x2 (quote ( ) ) ) ) . How can you build a pair with two Sexpressions? You cons the first one onto the cons of the second one onto () . ( cons x1 ( cons x2 (quote ( ) ) ) ) . ( apair? l ) where l is (fu l l (house)) #t . . because it is a list with only two Sexpressions. No.
They will be used to improve readability. We use rei to stand for relation . See chapter 6. Is l a rei where l is ( (a pples peaches) (pumpkin pie) (apples peaches) ) No . and build as oneliners. second .(define first (lambda (p) ( cond (else ( car p))))) (define second (lambda (p) (cond (else ( car ( cdr p ) ) ) ) ) ) (define build (lambda (sl s2 ) (cond ( else ( cons sl ( cons s2 (quote ( ) ) ) ) ) ) ) ) What possible uses d o these three functions have? Can you write third as They are used to make representations of pairs and to get parts of representations of pairs. since l i s not a list of pairs. Is l a rei where l is ((apples peaches) (pum pki n pie) ) Yes. since l is not a set of pairs. Redefine first. a oneliner? ( define third (lambda ( l ) ( car ( cdr ( cdr l))))) Is l a rei where l is (apples peaches pumpkin pie) No. Friends and Relations 119 . Is l a rei where l is ( (4 3) (4 2) (7 6) (6 2) (3 4) ) Yes. as you will soon see.
What i s (fun ? rel) where rel is ((d 4) (b 0) (b 9) (e 5) (g 4) ) #f. What i s (fun ? rel) where rel is ((8 3) (4 2) (7 6) (6 2) (3 4) ) #t . Write fun ? with set ? and firsts (define fun ? (lambda ( rel) (set? (firsts rel) ) ) ) Is fun ? a simple oneliner? How do we represent a finite function? I t sure is. because (firsts rel) is a set See chapter 3 . We use fun to stand for function. You can now write revrel (define revrel (lambda ( rel) (cond ( ( null? rel) (quote ())) (else ( cons ( build (second ( car rel)) (first ( car rel))) ( revrel ( cdr rel) )))))) 120 Chapter 7 . because b is repeated. a finite function is a list of pairs in which no first element of any pair is the same as any other first element . What is ( revrel rel) where rel is ( (8 a) (pumpkin pie) (got sick)) (( a 8) (pie pumpkin) (sick got ) ) . For us.Is rel a fun where rel is ((4 3) (4 2) (7 6) (6 2) (3 4) ) No.
Friends and Relations 121 . but now do you see how representation aids readability? (define revrel (lambda ( rel) (cond ( ( null? rel) (quote ( ) ) ) (else ( cons ( cons ( car ( cdr ( car rel) ) ) ( cons ( car ( car rel)) (quote ( ) ) ) ) ( revrel ( cdr rel) ) ) ) ) ) ) Suppose we had the function revpair that reversed the two components of a pair like this: No problem . and it is even easier to read: ( define revrel (lambda ( rel) ( cond ( ( null? rel) (quote ())) ( else ( cons ( revpair ( car rel) ) ( revrel ( cdr rel))))))) (define revpair (lambda (pair) ( build (second pair) (first pair)))) How would you rewrite revrel to use this help function? Can you guess why fun is not a fullfun where fun is ( (8 3) (4 2) (7 6) (6 2) (3 4) ) fun is not a fullfun. since the 2 appears more than once as a second item of a pair. What is (fullfun '? fun) where fun is ( (grape raisin) (pl u m prune) (stewed prune) ) #f.Would the following also be correct: Yes. Why is #t the value of (fullfun ? fun) where fun is ( (8 3) (4 8) (7 6) (6 2) (3 4) ) Because (3 8 6 2 4) is a set .
Can you think of a second way to write onetoone ? (define onetoone ? (lambda (fun) (fun ? ( revrel fun) ) ) ) Is ((chocolate chip) (doughy cookie)) a onetoone function? Yes. because ( raisin prune grape) is a set. and you deserve one now! Go and get one! 122 Chapter 7 . Define fullfun ? (define fullfun ? (lambda (fun) (set? (seconds fun) ) ) ) Can you define seconds I t i s just like firsts . What is another name for fullfun ? onetoone ?.What is (fullfun ? fun) where fun is ( (gra pe raisi n) (plum prune) (stewed grape)) #t .
O r b etter yet .powder 1 teaspoon)) (quote (bakingsoda 1 teaspoon) ) ) ( mix (quote (eggs 2 large)) (quote (vanilla 1 teaspoon)) ( cream (quote (butter 1 cup)) (quote (sugar 2 cups)) ) )))))) Friends and Relations 123 .5 teaspoon) ) (quote (ba king. make your own . (define cookies (lambda () ( bake (quote (350 degrees)) (quote ( 12 minutes)) ( mix (quote (walnuts 1 cup)) (quote (chocolatechips 16 ounces)) ( mix ( mix (quote (flou r 2 cups)) (quote (oatmeal 2 cups) ) (quote (salt .
.
Lambda the Ultimate 125 . (6 2 3) . By passing equal? as an argument to rembert . because we have not yet told you how. By passing c and (b c a) as arguments to rember. L : (remberf (function but there is more. 1 • ) 5 ' (6 2 5 3) ) . By passing a and (b c a) as arguments to rember. What is ( rembert test? a l) where test? is eq? a is jelly and l is Uelly beans are good) And what is ( rembert test? a l) where test ? is equal? a is (pop corn) and l is (lemonade (pop corn ) and (cake)) ( beans are good ) . ( lemonade a n d (cake) ) .Remember what we did in rember and inserlL at the end of chapter 5? Can you write a function rembert that would use either eq ? or equal ? How can you make rember remove the first a from (b c a ) How can you make rember remove the first c from (b c a) How can you make rembert use equal ? instead of eq? What is ( rembert test ? a l) where test? is = 1 a is 5 and l is (6 2 5 3) We replaced eq ? with equal? No.
Try to write remberf (define remberf (lambda ( test ? a l) (cond ( ( null ? l) (quote ())) (else (cond ( ( test ? ( car l) a) 1 ( cdr l)) (else ( cons ( car l) ( remberf test ? a ( cdr l))))))))) This is good! 1 L : (funcall t e s t ? (car 1 ) a) . 1 26 Chapter 8 . This is j ust rember with eq ? replaced by equal ?. Yes: rember with = rember with equal ? rember with eq ? and remberf . acts like rember. What about the short version? (define remberf (lambda ( test ? a l) (cond ( ( null ? l) (quote ( ) ) ) ( ( test? ( car l) a) ( cdr l)) (else ( cons ( car l) ( remberf test ? a ( cdr l))))))) How does ( remberf test ? a l) act where test? is eq ? And what about ( remberf test? a l) where test? is equal? Now we have four functions that do almost the same thing. ( remberf test? a l) where test? is eq ?. U s e funcall when invoking a function argument or a function that has not been defuned .
Can you say what (lambda ( a l) . ) give the preceding function a name. Lists and atoms. Yes. ." Using (define . It is a function that. returns the function Now what is (lambda ( a ) (lambda ( x ) ( eq? x a ))) (lambda ( x ) ( eq? x a )) where a is just that argument . . Moses Schonfinkel ( 18891942 ) . a and l. 1 L: (defun eq?c (a) (funct ion (lambda (x) (eq x a) ) ) ) What is ( eq?c k) where k is sa lad Its value is a function that takes x as an argument and tests whether it is eq ? to salad . . Thank you. but you probably did not know that yet . ) is? (lambda ( a l) . . Haskell B. ) is a function of two arguments. (define eq ?c 1 (lambda ( a ) (lambda ( x ) ( eq? x a )))) This i s our choice. .And remberf can behave like all the others. Lambda the Ultimate 127 . It is not called "Schonfinkeling. when passed an argument a. Curry (19001982) . I s this called "Currying?" Thank you. . What kind of values can functions return? What about functions themselves? Let 's generate all versions with remberf .
(define 1 eq ?salad ( eq?c k)) where k is salad 1 L: ( setq eq?salad (eq?c ' salad) } . Now rewrite rembert as a function of one argument test? that returns an argument like rember with eq ? replaced by test? (define rembert (lambda ( test ?) (lambda ( a l) ( c ond ( ( null? l) (quote ( ) ) ) ( ( test ? ( car l) a) ( cdr l)) (else ( cons ( car l) . since (eq?c x) i s a function that has not been defuned. Use setq to define a function that can be funcalled. And what is ( eq ?salad y) where y is tuna Do we need to give a name to eq ?salad # f. 128 Chapter 8 .) Okay. What is ( eq ?salad y) 1 where y is salad #t . . 1 L : (funcall (eq?c x) y ) .salad has n o t been defuned . No. we may just as well ask ( ( eq ?c x) y) 1 where x is sa lad and y is tuna.I So let 's give it a name using (define . 1 L : (funcall eq?salad y ) .. since eq?.. )))))) is a good start. .
complete the line ( cons ( car l) . (define rembereq ? ( remberf test ?) ) where test ? is eq ?. and the first one that is eq ? to a is removed. Lambda the Ultimate 129 .Describe in your own words the result of ( remberf test ?) where test? is eq? Give a name to the function returned by ( remberf test ?) where test? is eq? It is a function that takes two arguments. Now. (sa lad is good ) . What is ( rembereq? a l) where a is tuna and l is (tuna salad is good) Did we need to give the name rembereq? to the function ( remberf test ?) where test? is eq? No. . It compares the elements of the list with a. we could have written ( ( remberf test ?) a l) where test? is eq ? a is tuna and l is (tuna salad is good ) . a and l. ) in remberf so that remberf works. (define remberf (lambda ( test ?) (lambda ( a l) (cond ( ( null ? l) (quote ( ) ) ) ( ( test ? ( car l) a) ( cdr l)) (else ( cons ( car l) ( ( remberf test ?) a ( cdr l ) ) ) ) ) ) ) ) What is ( ( remberf eq ?) a l) where a is tuna and l is (shri m p salad and tuna salad) (shri m p salad and sa lad ) . .
get yourself some coffee cake and relax! Otherwise.What is ( ( remberf eq ?) a l) where a is eq? and l is (equal? eq ? eqan? eq list? eqpair? ) 1 1 Did you notice the difference between eq? and eq ? Remember that the former is the atom and the latter is the function. You'll see it in a minute. And now transform insertL to insertLf the same way we have transformed rember into remberf (define insertLf (lambda ( test ?) (lambda ( new old l) (cond ( ( null? l) (quote ())) ( ( test ? ( car l) old) ( cons new ( cons old ( cdr l)))) (else ( cons ( car l) ( ( insertLf test ?) new old ( cdr l)))))))) And. 130 Chapter 8 . do it to insertR (define insertRf (lambda ( test ?) (lambda ( new old l) (cond ( ( null? l) (quote ())) ( ( test ? ( car l) old ) ( cons old ( cons new ( cdr l)))) (else ( cons ( car l) ( ( insertRf test ?) new old ( cdr l)))))))) Are insertR and insertL similar? Can you write a function insertg that would insert either at the left or at the right? Only the middle piece is a bit different . If you can. (equal? eqan? eqlist? eqpair? ) . j ust for the exercise. don't give up.
Put the difference in words! So how can we get rid of the difference? Define a function seqL that 1. We say: "The two functions cons old and new in a different order onto the cdr of the list l. takes three arguments. but in insertR it is: ( ( eq ? ( car l) old ) ( cons old ( cons new ( cdr l ) ) ) ) . conses the second argument onto the result of cons ing the first argument onto the third argument. Do you know why we wrote these functions? Lambda the Ultimate 131 . What is: (define seqL (lambda ( new old l) ( cons new ( cons old l)))) (define seqR (lambda ( new old l) ( cons old ( cons new l)))) A function that 1 ." You probably guessed it: by passing in a function that expresses the appropriate cons ing. In insertL it is: ( ( eq ? ( car l) old) ( cons new ( cons old ( cdr l))) ) . takes three arguments. cons es the first argument onto the result of cons ing the second argument onto the third argument. and 2. and 2. Because they express what the two differing lines in insertL and insertR express.Which pieces differ? The second lines differ from each other.
Earlier we would probably have written (define insertL ( insertg seq)) where seq is seqL and (define insertR ( insertg seq)) where seq is seqR. Not really. (define insertL ( insertg (lambda ( new old l) ( cons new ( cons old l))))) 132 Chapter 8 . (define insertR ( insertg seqR)) Is there something unusual about these two definitions? Yes. Is it necessary to give names to seqL and seqR Define insertL again with insertg Do not pass in seqL this time. We could have passed their definitions instead. using "where" is unnecessary when you pass functions as arguments. But.Try to write the function insertg of one argument seq which returns insertL where seq is seqL and which returns insertR where seq is seqR (define insertg (lambda (seq) {lambda ( new old l) ( c ond ( ( null? l) (quote ())) ( ( eq ? ( car l) old) (seq new old ( cdr l))) (else ( cons ( car l) ( ( insertg seq) new old ( cdr l)))))))) Now define insertL with insertg (define insertL ( insertg seqL) ) And insertR .
Just the answer of the second condline is different . Here is one. because you do not need to remember as many names. Do you remember the definition of subst (define subst (lambda ( new old l) (cond ( ( null ? l) (quote ( ) ) ) ( ( eq ? ( car l) old ) ( cons new ( cdr l))) (else ( cons ( car l) ( subst new old ( cdr l))))))) Does this look familiar? Yes. What role does # f play? (define yyy (lambda ( a l) ( ( insertg seqrem) #f a l))) where ( define seqrem (lambda ( new old l) l)) Lambda the Ultimate 133 . You can ( rember Junename "yourmind" ) where Junename is seqL.Is this better? Yes. What do you think about this? Define a function like seqL or seqR for subst (define seqS (lambda ( new old l) ( cons new l))) And now define subst using insertg (define subst ( insertg seqS)) And what do you think yyy is Surprise! It is our old friend rember Hint : Step through the evaluation of ( yyy a l) where a is sa usage and l is ( pizza with sa usage and bacon) . i t looks like insertL o r insertR .
What you have j ust seen is the power of abstraction. x . we have even seen functions with similar lines. Have we seen similar functions before? Yes. The Nint h Commandment Abstract common patterns with a new function. and t . Takes one argument x and 2. returns the function + if ( eq? x (quote + ) ) returns the function x if ( eq ? x (quote x )) and returns the function t otherwise? (define atomtofunction (lambda (x) ( cond ( ( eq? x (quote +)) + ) ( ( eq ? x (quote x )) x ) ( else t ) ) ) ) 134 Chapter 8 . Can you write the function atomtofunction which: 1 . Do you remember value from chapter 6? (define value (lambda ( nexp) (cond ( ( atom ? nexp) nexp) ( ( eq ? ( operator nexp) (quote +)) ( + ( value ( 1stsubexp nexp)) ( value ( 2ndsubexp nexp)))) ( ( eq? ( operator nexp) (quote x ) ) ( x ( value ( 1stsubexp nexp)) ( value ( 2ndsubexp nexp)))) (else ( t ( value ( 1stsubexp nexp)) ( value ( 2ndsubexp nexp) )))))) Do you see the similarities? The last three answers are the same except for the + .
No problem . (define value (lambda ( nexp) (cond ( ( atom ? nexp) nexp) (else ( ( atomtofunction ( operator nexp)) ( value ( 1 stsubexp nexp)) ( value ( 2ndsubexp nexp ) ) ) ) ) ) ) Is this quite a bit shorter than the first version? Time for an apple? Here is multirember again. We haven't changed its meaning. Lambda the Ultimate 135 . Yes.What is ( atomtofunction ( operator nexp)) where nexp is ( + 5 3) Can you use atomtofunction to rewrite value with only two condlines? The function + . not the atom + . (define multirember (lambda ( a lat) ( cond ( ( null? lat) (quote ())) ( ( eq? ( car lat) a) ( multirember a ( cdr lat))) (else ( cons ( car lat) ( multirember a ( cdr lat))))))) Write multiremberf (define multiremberf (lambda ( test ?) (lambda ( a lat) ( c ond ( ( null? lat) (quote ( ) ) ) ( ( test ? a ( car lat )) ( ( multiremberf test ?) a ( cdr lat ))) (else ( cons ( car lat) ( ( multiremberf test?) a ( cdr lat) ) ) ) ) ) ) ) What is ( ( multiremberf test?) a lat) where test? is eq? a is tuna and lat is (shri m p sa lad tuna sa lad and tuna) (shri m p sa lad sa lad and ) . but that 's okay. One a day keeps the doctor away. O f course.
Wasn't that easy? Define multirembereq ? using multiremberf Yes. (quote + ) . 0. (quote more. test? always stands for eq?. and many 136 Chapter 8 . The new test? takes one argument and compares it to tuna. Do we really need to tell multiremberf about tuna Does test ? change as multiremberf goes through lat Can we combine a and test? As multiremberf visits all the elements in lat . No. (define multirembereq? ( multiremberf test?) ) where test? i s eq ?. and here is a different way: How would it do that? Here is one way to write this function. Well. Yes. just as a always stands for tuna. where k is tuna Can you think of a different way of writing this function? Have you ever seen definitions that contain atoms? Yes. it always looks for tuna. I (define <q ?tuno ( eq?c k)) (define eq ?tuna ( eq?c (quote tuna ) ) ) . test? could be a function of just one argument and could compare that argument to tuna. x ) .
multiremberT takes a function like eq?tuna and a lat and then does its work. Now that looks really complicated! (define multirember&co (lambda ( a lat col) (cond ( ( null? lat) ( col ( quote ()) (quote ()))) ( ( eqP ( car lat) a) ( multirember&co a ( cdr lat) (lambda ( newlat seen) ( col newlat ( cons ( car lat) seen))))) ( else ( multirember&co a ( cdr lat) (lambda ( newlat seen) ( col ( cons ( car lat) newlat) seen) ) ) ) ) ) ) Lambda the Ultimate 137 . It 's not bad. This is not really difficult.Perhaps we should now write multiremberT which is similar to multiremberf Instead of taking testP and returning a function. (define multiremberT (lambda ( test ? lat) (cond ( ( null ? lat) (quote ( ) ) ) ( ( test ? ( car lat) ) ( multiremberT test ? ( cdr lat))) (else ( cons ( car lat) ( multiremberT test? ( cdr lat) ) ) ) ) ) ) What is ( multiremberT test ? lat) where test? is eq ?tuna and lat is (shri m p salad tuna salad and tuna) Is this easy? How about this? (shri m p salad salad a nd ) .
The first one is clearly tuna . What is the value of ( multirember&co a lat col) where a is tuna lat is () and col is afriend This is not simple. It is a function that takes two arguments and asks whether the second one is the empty list. The name col is short for "collector." A collector is sometimes called a "continuation. it is simpler. What is the value of ( multirember&co a lat col) where a is tuna lat is (strawberries tuna and swordfish) and col is afriend So let 's try a friendlier example. Then it recurs on ( ) . The third argument is a new function. because afriend is immediately used in the first answer on two empty lists.Here is something simpler: (define afriend (lambda ( a: y) ( null? y))) Yes. And what is ( multirember&co a lat col) where a is tuna lat is (tuna) and col is afriend What are the other arguments that multirember&co uses for the natural recursion? What is the name of the third argument? Do you know what col stands for? multirember&co asks ( eqP ( car lat) (quote tuna )) where lat is (tuna). col." 138 Chapter 8 . It ignores its first argnment. and afriend makes sure that its second argument is empty. #t .
Which collector is this? How does afriend differ from newfriend newfriend uses afriend on the empty list and the value of ( cons (quote tuna) (quote ( ) ) ) . we can : (define newfriend (lambda ( newlat seen ) ( afriend newlat ( cons (quote tuna) seen)))) And now? multirember&co finds out that ( null ? lat ) is true. which means that it uses the collector on two empty lists. Yes. because its second argument is (tuna ) . I t answers #f. It is newfriend. And what does the old collector do with such arguments? What is the value of ( multirember&co a lat afriend) where a is tuna and lat is (and tuna) (define latestfriend (lambda ( newlat seen ) ( afriend ( cons (quote and) newlat) seen))) Lambda the Ultimate 139 . which is not the empty list . This time around multirember&co recurs with yet another friend.Here is the new collector: (define newfriend (lambda ( newlat seen) ( col newlat ( cons ( car lat) seen)))) where ( car lat) is tuna and col is afriend Can you write this definition differently? Can we also replace col with afriend in such definitions because col is to afriend what ( car lat) is to tuna Do you mean the new way where we put tuna into the definition? (define newfriend (lambda ( newlat seen) ( col newlat ( cons (quote tuna) seen)))) where col is afriend.
but we have seen foreign foods before. 140 Chapter 8 . Finally.And what is the value of this recursive use of multirember&co #f. the others for which the answer is true are collected in a second list ls2 . because ls contains three things that are not tuna. and therefore lastfriend is used on (strawberries and swordfish) and (tuna ) . The Tent h Commandment Build functions to collect more than one value at a time. 3. It looks at every atom of the lat to see whether it is eq ? to a. Those atoms that are not are collected in one list ls1 . it determines the value of (! ls1 ls2 ) . since ( afriend ls1 ls2) where ls1 is (and) and ls2 is (tuna) is #f. What does ( multirember&co a lat f) do? Final question: What is the value of ( multirember&co (quote tuna) ls col) where ls is (strawberries tuna and swordfish) and col is (define lastfriend (lambda ( x y) ( length x ) ) ) Yes! It's a strange meal.
(define multiinsertL (lambda ( new old lat) (cond ( ( null? lat) (quote ())) ( ( eq ? ( car lat) old ) ( cons new ( cons old ( multiinsertL new old ( cdr lat))))) (else ( cons ( car lat) ( multiinsertL new old ( cdr lat) ) ) ) ) ) ) D o you also remember multiinsertR Now try multiinsertLR Hint: multiinsertLR inserts new to the left of oldL and to the right of oldR in lat if oldL are oldR are different . (define multiinsertLR (lambda ( new oldL oldR lat) (cond ( ( null? lat) ( quote ( ) ) ) ( ( eq? ( car lat) oldL) ( cons new ( cons oldL ( multiinsertLR new oldL oldR ( cdr lat ) ) ) ) ) ( ( eq ? ( car lat) oldR) ( cons oldR ( cons new ( multiinsertLR new oldL oldR ( cdr lat ) ) ) ) ) (else ( cons ( car lat) ( multiinsertLR new oldL oldR ( cdr lat ) ) ) ) ) ) ) The function multiinsertLR&co i s to multiinsertLR what multirember&co is to multirember Yes. Lambda the Ultimate 141 . No problem.Here is an old friend. and what kind of argument is it? Does this mean that multiinsertLR&co takes one more argument than multiinsertLR? It is a collector function. (define multiinsertR (lambda ( new old lat) (cond ( ( null ? lat) (quote ())) ( ( eq ? ( car lat) old ) ( cons old ( cons new ( multiinsertR new old ( cdr lat ) ) ) ) ) (else ( cons ( car lat) ( multiinsertR new old ( cdr lat ) ) ) ) ) ) ) This i s a way of combining the two functions.
the first is the lat that multiinsertLR would have produced for ( cdr lat ) . So what is the value of ( multiinsertLR &co ( quote cranberries) ( quote fish ) ( quote chi ps) ( quote ()) col) Is it true that multiinsertLR &co will use the new collector on three arguments when ( car lat) is equal to neither oldL nor oldR Yes. . . It is the value of ( col (quote ( )) 0 0) . And this means that 0 occurrences of oldL and 0 occurrences of oldR are found and that multiinsertLR will return () when lat is empty. Can you write an outline of multiinsertLR &co Sure. (define multiinsertLR&co (lambda ( new oldL oldR lat col) (cond ( ( null? lat) ( col ( quote ()) 0 0)) ( ( eq? ( car lat) oldL) ( multiinsertLR&co new oldL oldR ( cdr lat) (lambda ( newlat L R) . and the number of right insertions. . 142 Chapter 8 . ))) ( ( eq ? ( car lat) oldR) ( multiinsertLR&co new oldL oldR ( cdr lat) (lambda ( newlat L R) . and oldR . .When multiinsertLR&co is done. ))) ( else ( multiinsertLR&co new oldL oldR ( cdr lat) (lambda ( newlat L R) . which we cannot determine because we don't know what col is. on the number of left insertions. it will use col on the new lat . respectively. oldL. The second and third are the number of insertions that occurred to the left and right of oldL and oldR . . it is just like multiinsertLR. . )))))) Why is col used on ( quote ( ) ) 0 and 0 when ( null? lat) is true? The empty lat contains neither oldL nor oldR .
it is true. . Lambda the Ultimate 143 . L and R are the correct results for both ( cdr lat) and all of lat .Is it true that multiinsertLR&co then uses the function col on ( cons ( car lat) newlat) because it copies the list unless an oldL or an oldR appears? Why are col's second and third arguments just L and R Yes. Instead of adding one to L. If ( car lat) i s neither oldL nor oldR . it cons es oldR onto the result of cons ing new onto newlat . Here is what we have so far. So. ))) (else ( multiinsertLR&co new oldL oldR ( cdr lat) (lambda ( newlat L R) ( col ( cons ( car lat) newlat) L R))))))) Can you fill in the dots? So can you fill in the dots? Yes. and instead of cons ing new onto cons ing oldL onto newlat . And we have even thrown in an extra collector: (define multiinsertLR&co (lambda ( new oldL oldR lat col) ( cond ( ( null? lat) ( col (quote ( ) ) 0 0)) ( ( eq? ( car lat) oldL) ( multiinsertLR&co new oldL oldR ( cdr lat) (lambda ( newlat L R) ( col ( cons new ( cons oldL newlat)) ( add1 L) R)))) ( ( eq? ( car lat) oldR) ( multiinsertLR&co new oldL oldR ( cdr lat) (lambda ( newlat L R) . we do not need to insert any new elements. it adds one to R. so we know what the new collector for the last case is: (lambda ( newlat L R) ( col ( cons ( car lat) newlat) L R ) ) . . The incomplete collector is similar to the extra collector. the final collector is (lambda ( newlat L R) ( col ( cons oldR ( cons new newlat) ) L ( add1 R ) ) ) .
empty. or . Here is even ? (define even ? (lambda (n) ( = ( x (+ n 2) 2) n))) (define evensonly * (lambda (l) (cond ( ( null ? l) (quote ())) ( ( atom ? ( car l)) (cond ( ( even ? ( car l)) ( cons ( car l) ( evensonly * ( cdr l)))) ( else ( evensonly * ( cdr l))))) (else ( cons ( evensonly * ( car l)) ( evensonly * ( cdr l))))))) What is the value of ( evensonly * l) where l is ( (9 1 2 8) 3 10 ( (9 9 ) 7 6) 2) ((2 8) 10 ( ( ) 6) 2).only * is just an exercise: Do you remember what *functions are? Now write the function evensonly * which removes all odd numbers from a list of nested lists. evens. Perhaps dessert is sweeter. Now that we have practiced this way of writing functions. Yes. 144 Chapter 8 . . Looks like lots of salt. all *functions work on lists that are either .an atom consed onto a list .a list consed onto a list.What is the value of ( multiinsertLR&co new oldL oldR lat col) where new is sa lty oldL is fish oldR is chips and lat is (chips and fish or fish and chi ps) Is this healthy? It is the value of ( col newlat 2 2) where newlat is (ch i ps salty and salty fish or sa lty fish and chips salty).
What does the function evensonly *&co do after visiting all the numbers in ( car l) It uses the collector. which we haven't defined yet . Can you explain what ( evensonly *&co ( car l) . . ))))) . and the sum of the odd numbers. . 2 X 8 X 10 X 6 X 2 = 1920. It visits every number in the car of l and collects the list without odd numbers. Lambda the Ultimate 145 . This is full of stars! (define evensonly *&co (lambda ( l col) (cond ( ( null? l) ( col (quote ()) 1 0)) ( ( atom ? ( car l)) fcond ( ( even ? ( car l)) ( evensonly *&co ( cdr l) (lambda ( newl p s ) ( col ( cons ( car l) newl) ( x ( car l) p) s ) ) ) ) (else ( evensonly *&co ( cdr l) (lambda ( newl p s ) ( col newl p ( + ( car l) s ) ) ) ) ) ) ) (else ( evensonly *&co ( car l ) . Here is an outline. ) accomplishes? 9+1+3+9+9+7 = 38.What is the sum of the odd numbers in l where l is ( ( 9 1 2 8) 3 10 ( ( 9 9 ) 7 6) 2) What is the product of the even numbers in l where l is ( ( 9 1 2 8) 3 10 ( ( 9 9 ) 7 6) 2) Can you write the function evensonly *&co It builds a nested list of even numbers by removing the odd ones from its argument and simultaneously multiplies the even numbers and sums up the odd numbers that occur in its argument . . the product of the even numbers.
. Does this mean the unknown collector looks roughly like this: (lambda ( al ap as ) ( evensonly *&co ( cdr l) . ) do? The yettobedetermined collector is used.And what does the collector do? It uses evensonly *&co to visit the cdr of l and to collect the list that is like ( cdr l). )) And when ( evensonly *&co ( cdr l) . ) is done with its job. what happens then? What does the collector for ( evensonly *&co ( cdr l) . Then it passes these values to the old collector: (lambda ( al ap as ) ( evensonly *&co ( cdr l) (lambda ( dl dp ds ) ( col ( cons al dl) ( x ap dp) ( + as ds ) ) ) ) ) . (define thelastfriend (lambda ( newl product sum) ( cons sum ( cons product newl)))) 146 Chapter 8 . It conses together the results for the lists in the car and the cdr and multiplies and adds the respective products and sums. Yes. . without the odd numbers of course. Does this all make sense now? What is the value of ( evensonly *&co l thelastfriend) where l is ( ( 9 1 2 8) 3 10 ( ( 9 9 ) 7 6) 2) and thelastfriend is defined as follows: (38 1920 (2 8) 10 (() 6) 2) . . . Perfect . . as well as the product of the even numbers and the sum of the odd numbers. . just as before.
Lambda the Ultimate 147 . don't forget the mustard.Whew! Is your brain twisted up now? Go eat a pretzel.
.
3. and Again. . because the third element is grits. ( looking a lat) where a is caviar and lat is (6 2 grits caviar 5 7 3) Were you expecting something different? True enough. Yes. 6. . . and Again. . Here is looking (define looking (lambda ( a lat) (keeplooking a (pick 1 lat) lat) ) ) Write keeplooking ( looking a lat) where a is caviar md lat is (6 2 4 caviar 5 7 3) #t . which does not even resemble caviar. caviar is obviously in lat .Are you in the mood for caviar What is ( looking a lat) where a is caviar and lat is (6 2 4 caviar 5 7 3) Then we must go looking for it. but what is the first number in the lat? And what is the sixth element of lat And what is the seventh element? So looking clearly can't find caviar #f. 7. We did not expect you to know this. . because (keeplooking a 6 lat) has the same answer as (keeplooking a (pick 1 lat) lat) . #t . True enough . caviar is still in lat . 149 . and Again. .
So what do we do? (keeplooking a 7 lat) where a is caviar and lat is (6 2 4 caviar 5 7 3). It is truly unnatural.What is (pick 6 lat) where lat is (6 2 4 caviar 5 7 3) 7. Which is? #t . So what is (keeplooking a 3 lat) where a is caviar and lat is (6 2 4 caviar 5 7 3) It is the same as (keeplooking a 4 lat). Write keeplooking (define keeplooking (lambda ( a sorn lat) (cond ( ( number? sorn) (keeplooking a (pick sorn lat) lat)) (else ( eq ? sorn a))))) Can you guess what sorn stands for? Symbol or number. What is unusual about keeplooking It does not recur on a part of lat. We call this "unnatural" recursion. What is (pick 7 lat) where lat is (6 2 4 caviar 5 7 3) 3. 150 Chapter 9 .
and Again. What do you think the functions we have seen so far are called? They are called total. Does it always get closer to its goal? Sometimes the list may contain neither caviar nor grits. Yes. . Can you define a shorter function that does not reach its goal for some of its arguments? (define eternity (lambda ( x ) ( eternity x ))) For how many of its arguments does eternity reach its goal? None. . That is correct. . and Again. we will never stop looking. Functions like looking are called partial functions. What is ( looking a lat) where a is caviar and lat is (7 1 2 caviar 5 6 3) This is strange! Yes. . (a (b c) ) . .Does keeplooking appear to get closer to its goal? Yes. Is eternity partial? What is (shift x ) where x is ((a b) c) It is the most partial function. it is strange. 151 . . if we start looking in (7 2 4 7 5 6 3). What happens? We keep looking and looking and looking . . A list may be a tup. and Again. from all available evidence. and this i s the most unnatural recursion possible. .
Define shift This i s trivial. it's not even recursive! (define shift (lambda (pair) ( build (first (first pair)) ( build (second (first pair)) ( second pair))))) Describe what shift does. Why are we not guaranteed that align makes progress? In the second c ond. 152 Chapter 9 ." Now look at this function: (define align (lambda (pora) (cond ( ( atom? pora) pora) ( ( apair? (first pora) ) ( align (shift pora))) (els e ( build (first pora) ( align (second pora ) ) ) ) ) ) ) What does i t have i n common with keeplooking Both functions change their arguments for their recursive uses but in neither case is the change guaranteed to get us closer to the goal.What is (shift x ) where x is ( (a b) ( c d ) ) (a ( b (c d ) ) ) . Which commandment does that violate? The Seventh Commandment . Here are our words: "The function shift takes a pair whose first component is a pair and builds a pair by shifting the second part of the first component into the second component.line shift creates an argument for align that is not a part of the original argument .
How much more attention should we pay to the first component? At least twice as much. . . The first component of a pair becomes simpler. and Again. there is. and Again. There may b e arguments for which it keeps aligning things. though the second component becomes more complicated. . and Again. 153 . . Is there something else that changes about the arguments to align and its recursive uses? Yes. In what way is the first component simpler? It is only a part of the original pair's first component .Is the new argument at least smaller than the original one? It does not look that way. Doesn't this mean that length * is the wrong function for determining the length of the argument? Can you find a better function? A better function should pay more attention to the first component. No problem : Can you write a function that counts the number of atoms in align 's arguments? (define length * (lambda (pora) (cond ( ( atom ? pora) 1 ) (else ( + ( length * (first porn) ) ( length * (second porn ) ) ) ) ) ) ) Is align a partial function? We don 't know yet. . Why not? The function shift only rearranges the pair it gets. And? Both the result and the argument of shift have the same number of atoms. .
(define weight* (lambda (pora) (cond ( ( atom ? pora) 1) (else ( + ( x ( weight* (first pora) ) 2) ( weight* (second pora ) ) ) ) ) ) ) What i s ( weight * x ) where x is ( ( a b ) c ) And what is ( weight* x ) where x is ( a (b c ) ) 7. it yields a value for every argument . the weight * 's of align's arguments become successively smaller.Do you mean something like weight* That looks right . Is align a partial function? No. 5. 154 Chapter 9 . instead of shift : The functions shujjle and revpair swap the components of pairs when the first component is a pair. (define shujjle (lambda (pora) (cond ( ( atom ? pora) pora) ( ( apair? (first pora)) ( shujjle ( revpair pora))) (else ( build (first pora) ( shujjle ( second pora) ) ) ) ) ) ) Does this mean that shujjle i s total? We don't know. Does this mean that the arguments get simpler? Yes. Here is shujjle which is like align but uses revpair from chapter 7.
What is the value of ( shuffte x) where x is (( a b) ( c d ) ) To determine this value. Lothar Collatz ( 19101990) .Let 's try it . let 's try something interesting. Doesn't this mean that we need to know the value of ( shuffte ( revpair pora) ) where (revpair pora) is (( a b) ( c d ) ) Yes. Thank you. And? The function shuffte is not total because it now swaps the components of the pair again. . which means that we start all over. . but otherwise nobody knows. and Again. (shuffte x) where x is (a b) ( a b). Is this function total? (defi ne C (lambda (n) (co nd ( ( one ? n) 1 ) (else (cond (( even ? n) ( C (+ n 2 ) ) ) (else ( C ( add1 ( x 3 n)))) ) ) ) ) ) It doesn 't yield a value for 0. and Again. 155 . we do. we need to find out what ( shuffte ( revpair pora)) is where pora is ((a b) ( c d ) ) . . . Okay. . What is the value of (shuffte x) where x is (a (b c )) ( a ( b c )) . And how are we going t o d o that? We are going t o determine the value of ( shuffte pora) where pora is (( c d ) ( a b) ) . . and Again.
there is no answer. 3. Yes. do not necessarily decrease for the recursion. Does A always give an answer? Then what is ( A 4 3) What does that mean? But answer came there noneAnd this was scarcely odd. The Walrus and The Carpenter Lewis Carroll 156 Chapter 9 . The page that you are reading now will have decayed long before we could possibly have calculated the value of ( A 4 3). (A 1 1) ( A 2 2) Here is the definition of A (define A (lambda ( n m) (cond ( ( zero ? n) ( addl m)) ( ( zero ? m) ( A ( subl n) 1)) (else ( A (subl n) ( A n ( subl m ) ) ) ) ) ) ) What does A have i n common with shuffie and looking How about an example? A 's arguments. And that means we need the value of ( A 0 3). Wilhelm Ackermann (18531946) .What is the value of ( A 1 0) 2. 7. because They 'd eaten every one. it is total. That 's easy: ( A 1 2) needs the value of ( A 0 ( A 1 1 ) ) . like shuffie 's and looking's. For all practical purposes. Thank you .
and Again. That would simplify it a lot . Here is the beginning of this function: What does it do? (define willstop ? (lambda U ) . and Again. What is the value of ( willstop ? f ) where f is length We know that ( length l) is 0 where l is ( ) . A function can work for many different arguments. . 157 . .Wouldn't it be great if we could write a function that tells us whether some function returns with a value for every argument ? It sure would. and Again. . It sounds complicated. Then let's make it simpler. . Then let's make up some examples. . . we should have some tool like this around. For a warmup exercise. Is willstop ? total then? Yes. . Here is the first one. . Now that we have seen functions that never return a value or return a value so late that it is too late. let 's focus on a function that checks whether some function stops for just the empty list . Okay. depending on whether the argument stops when applied to ( ) . let's write it . I t always returns #t o r #f. i t i s . )) Can you fill in the dots? Does willstop ? return a value for all arguments? That's the easy part : we said that it either returns #t or #f. the simplest of all arguments. So? Then the value o f ( willstop ? length) should be #t .
we must determine the value of (and ( willstop ? lasttry) ( eternity (quote ( ) ) ) ) . Okay. 158 Chapter 9 . Do we need more examples? Perhaps we should do one more example. We just saw that. We said that the value of ( willstop ? lasttry) was #f. ) is always #f. since (and #f . here is a function that could be an interesting argument for willstop ? What does it do? (define lasttry (lambda ( x ) (and ( willstop ? lasttry) ( eternity x )))) What i s ( willstop ? lasttry) We need to test it on () If we want the value of ( lasttry (quote ())) . . How about another example? What is the value of ( willstop ? eternity) ( eternity (quote ())) doesn 't return a value. right? Yes. What is the value of (and ( willstop ? lasttry) ( eternity (quote ( ) ) ) ) That depends on the value of ( willstop ? lasttry) . . then (and #f ( eternity (quote ()))). it did. There are only two possibilities. it did. it does. is #f. But didn't willstop ? predict just the opposite? Yes. Does this mean the value of ( willstop ? eternity) is #f Yes. which really means that lasttry will not stop. Let 's say ( willstop ? lasttry) is #f Okay.Absolutely. So ( lasttry (quote ( ) ) ) stopped.
Thank you . It makes willstop ? the first function that we can describe precisely but cannot define in our language. But it cannotdue to the very definition of what willstop ? is supposed to do.So we must have been wrong about ( willstop ? lasttry ) That 's correct . We said it was total. and Again. Now we j ust need to determine the value of (and #t ( eternity (quote ( ) ) ) ) . which i s the same as the value of ( eternity (quote ( ) ) ) . . because willstop ? always gives an answer. . It must return #t . then ( willstop ? lasttry ) must yield either #t or #f. . . This must mean that willstop ? cannot be defined. . But that means we were wrong again! True. it is. Turing ( 1 9 1 21954) and Kurt Godel ( 19061978). Is this unique? Is there any way around this problem? No. Fine. We know that it doesn't stop. since this time we said that ( willstop ? lasttry ) was #t . and Again. What is (define . Alan M. ) doesn't work for willstop ?. What do you think this means? Here is our meaning: "We took a really close look at the two possible cases. If we can define willstop ?." Yes. If ( willstop ? lasttry ) is #t what is the value of ( lasttry (quote ( ) ) ) What i s the value o f ( eternity (quote ( ))) It doesn't have a value. ) This is an interesting question . 159 . . and Again. . . . We j ust saw that (define . .
) nothing. take a deep breath. It just won't give any answer for nonempty lists. we could try the following. .tY list and nothing else. If we give eternity an argument. . (lambda (l) (c o nd ( ( null ? l) 0) (else ( add1 ( eternity ( cdr l)))))) What happens when we use it on a nonempty list? What does it mean for this function that looks like length Suppose we could name this new function. and plunge forward when you're ready. lengtho because the function can only determine the length of the empty list . Is this the function length (define length (lambda (l) (cond ( ( null ? l) 0) (else ( add1 ( length ( cdr l))))))) What i f we didn't have (define . What would be a good name? No answer. . ) anymore? Could we still define length What does this function do? Without (define .So what are recursive definitions? Hold tight. It sure is. It determines the length of the emi. Well. . and especially not the body of length . How would you write a function that determines the length of lists that contain one or fewer items? (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( lengtho ( cdr l)))))) 160 Chapter 9 . could refer to length . it gives no answer.
(lambda (l) (cond ( ( null ? l) 0) (else ( add1 ( (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( eternity ( cdr l ) ) ) ) ) ) ( cdr l)))))) And what's a good name for this function? Is this the function that would determine the lenghts of lists that contain two or fewer items? That 's easy: length9 . Yes. . . (lambda (l) (cond ( ( null? l) 0) (else ( add1 ((lambda ( l) (cond ( ( null? l) 0) (else ( add1 ((lambda ( l) (cond ( ( null? l) 0) (else ( add1 ( eternity ( cdr l)))))) ( cdr l)))))) ( cdr l)))))) Now. . 161 . replace length0 by its definition. and Again. . . . what do you think recursion is? What do you mean? . .Almost. but (define . We just replace eternity with the next version of length . ) doesn't work for lengtho So. and Again. this is length�2 . and Again.
And we still have all these repetitions and patterns in these functions. But we can 't write an infinite function . Do you mean this? Yes. I t creates length0 . we have seen how to determine the length of a list with no items. or it contains one element . What do these patterns look like? All these programs contain a function that looks like length . . . How could we get the function length back? If we could write an infinite function in the style of lengtho . . Yes.Well. . a list is either empty. . ( ( lambda ( length) (lambda ( l ) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l))))))) eternity) 162 Chapter 9 . which would determine the length of all lists that we can make. . length 9 . . or 100 1 . . and so on. . Perhaps we should abstract out this function : see The Ninth Commandment . or three. that 's okay. . length 9 . . we do. then we could write length00 . How long are the lists that we can make? Well. ) . we can't. with no more than one item . . . Let 's do it ! We need a function that looks just like length but starts with (lambda ( length) . or two elements. or four. No. with no more than two items.
As long as we are consistent . .Rewrite length 9 in the same style. . How about length 9 ( ( lambda ( length ) (lambda (l) (cond ( ( null ? l) 0) (else ( add1 ( length ( cdr l ) ) ) ) ) ) ) ((lambda ( length) (lambda (l) (cond ( ( null ? l) 0) (else ( add1 ( length ( cdr l))))))) ((lambda ( length) (lambda ( l ) (cond ( ( null ? l) 0) (else ( add1 ( length ( cdr l ) ) ) ) ) ) ) eternity) )) Close. everything's okay. True. we just used f and g. Where should we start? Name the function that takes length as an argument and that returns a function that looks like length . and Again. . and Again. but there are still repetitions. and Again. . . 163 . . Let 's get rid of them . ( (lambda (/ ) (lambda (l) (cond ( ( null ? l) 0) (else ( add1 (/ ( cdr l))))))) ((lambda (g) (lambda (l) (cond ( ( null ? l) 0) (else ( add1 (g ( cdr l ) ) ) ) ) ) ) eternity) ) Do we have to use length to name the argument? No.
((lambda ( mklength) ( mklength eternity) ) (lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l)))))))) Is this length 9 It sure is. 164 Chapter 9 . And this is length9 . ( (lambda ( mklength) ( mklength ( mklength eternity) ) ) (lambda ( length) (lambda (l) (cond ( ( null ? l) 0) (else ( add1 ( length ( cdr l ) ) ) ) ) ) ) ) ((lambda ( mklength) ( mklength ( mklength ( mklength eternity) ) ) ) (lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l)))))))) Can you write length 9 i n this style? Sure. Here it is.What 's a good name for this function? Okay. ((lambda ( mklength) ( mklength ( mklength ( mklength ( mklength eternity) ) ) ) ) (lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l)))))))) What is recursion like? It is like an infinite tower of applications of mklength to an arbitrary function. do this to lengtho How about mklength for "make length" ? No problem.
Do we really need an infinite tower? Not really of course. but we never know how many. and Again. Everytime we use length we only need a finite number. 165 . . . . 1 1 With apologies t o George Orwell ( 1 903. When do we find out that we didn't guess a large enough number? When we apply the function eternity that is passed to the innermost mklength . how could we do that ? Well. That 's the right idea. Then is this still lengtho ((lambda ( mklength) ( mklength mklength)) (lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l)))))))) Yes. we could even use mklength instead of length . . but we may not guess a large enough number. . What if we could create another application of mklength to eternity at this point? That would only postpone the problem by one. Could we guess how many we need? Sure. ( (lambda ( mklength) ( mklength mklength )) (lambda ( mklength) (lambda ( l ) (cond ( ( null? l) 0) (else ( add1 ( mklength ( cdr l)))) ) ) ) ) Why would we want to do that? All names are equal.1950) . but some names are more equal than others. and Again. And then we invoke mklength on eternity and the result of this on the cdr so that we get one more piece of the tower. since nobody cares what function we pass to mklength we could pass it mklength initially. and Again. . and besides.
True: as long as we use the names consistently. Now that mklength is passed to mklength can we use the argument to create an additional recursive use? Yes. and we can do this as often as we need to! 166 Chapter 9 . Could we do this more than once? Yes. If we use a name like mklength . And mklength is a far more equal name than length . j ust keep passing mklength to itself. Work it out with paper and pencil. we are j ust fine. when we apply mklength once. it is a constant reminder that the first argument to mklength is mklength . we get length 9 ( (lambda ( mklength) ( mklength mklength)) (lambda ( mklength) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( ( mklength eternity) ( cdr l)))))))) What is the value of ( ( (lambda ( mklength ) ( mklength mklength)) (lambda ( mklength) (lambda (l) (cond ( ( null ? l) 0) (else ( add1 ( ( mklength eternity) ( cdr l )))))))) l) where l is (apples) This is a good exercise.
((lambda ( mklength) ( mklength mklength) ) (lambda ( mklength) (lambda (l) (cond ((null? l) 0) (else ( add1 ______. and Again. One problem is left: it no longer contains the function that looks like length We could extract this new application of mklength to itself and call it length . and Again. . . of course. just as it is about to expire. . I. ( (lambda ( mklength) ( mklength mklength) ) (lambda ( mklength) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( ( mklength mklength ) ( cdr l )))))))) H ow does i t work? It keeps adding recursive uses by passing mklength to itself.mklength mklength) I << ( cdr l)))))))) Can you fix that? Why? Because it really makes the function length . . .What would you call this function? It is length . 167 . and Again. .
How about this? Yes. First . this looks just fine. because the value of this expression is the function that we need to apply to l where l is (apples) 168 Chapter 9 . Okay. What is the value of ( ( (lambda ( mklength) ( mklength mklength) ) (lambda ( mklength) ((lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l ) ) ) ) ) ) ) ( mklength mklength)))) l) where l is (apples) It should be 1 . we need the value of ((lambda ( mklength) ( mklength mklength)) (lambda ( mklength) ( (lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l))))))) ( mklength mklength)))) That 's true. ((lambda ( mklength) ( mklength mklength) ) (lambda ( mklength) ((lambda ( length) (lambda (l) (cond ( ( null ? l) 0) (else ( add1 ( length ( cdr l))))))) ( mklength mklength)))) Let 's see whether it works.
So we really need the value of ((lambda ( mklength) ((lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l))))))) ( mklength mklength) ) ) (lambda ( mklength) ((lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l))))))) ( mklength mklength)))) But then we really need to know the value of ((lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l))))))) ((lambda ( mklength) ((lambda ( length) (lambda ( l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l))))))) ( mklength mklength))) (lambda ( mklength) ((lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l))))))) ( mklength mklength))))) True enough. Where is the end of this? Don't we also need to know the value of ( (lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l))))))) ((lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l))))))) ( (lambda ( mklength) ((lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l))))))) ( mklength mklength))) (lambda ( mklength) ( (lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l ) ) ) ) ) ) ) ( mklength mklength ) ) ) ) ) ) . and Again. and Again. Yes. and Again. . . . that 's true. 169 . too. . .
. there is no end to it . does (lambda ( x ) ( ( mklength mklength) x )) return a function of one argument? Actually. No it doesn 't.l ( k length mklength ) ( cdr l ) ) ) ) ) ) ) ) Here i s a different way. So what do we do? Turn the application of mklength to itself in our last correct version of length into a function : How? ((lambda ( mklength) ( mklength mklength) ) (lambda ( mklength) (lambda (l) (cond ( ( null ? l) 0) (else ( add1 (j'm__. is (lambda ( x ) (f x )) a function of one argument? Yes. (lambda ( x ) ( ( mklength mklength) i s a function! x )) 1 70 Chapter 9 . If ( mklength mklength) returns a function of one argument . it didn 't matter what we applied it to.Yes. . Indeed. But now that we have extracted ( mklength mklength) from the function that makes length it does not return a function anymore. Is this strange? It is because mklength used to return a function when we applied it to an argument. Why? Because we just keep applying mklength to itself again and again and again . If f i s a function of one argument . it is.
and Again.. . ((lambda ( mklength) ( mklength mklength ) ) (lambda ( mklength) ( (lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l ) ) ) ) ) ) ) (lambda (x) ( ( mklength mklength) x ) ) ) ) ) Is it okay to move out the function? Yes. we just always did the opposite by replacing a name with its value.:. Can we extract the function in the box that looks like length and give it a name? Yes.(. . ( 1ambd a' x ) ( ( mklength mklength) x)) ( cdr l)))))))) Move out the new function so that we get length back. . Here we extract a value and give it a name. it does not depend on mklength at all! . 171 .Okay. and Again. and Again. .. ((lambda ( mklength) ( mklength mklength) ) (lambda ( mklength) (lambda (l) (cond ( ( null ? l) 0) (else ( add1 ("'=. let's do this to the application of mklength to itself.. .
(define Y (lambda ( le) ((lambda (/ ) (/ f ) ) (lambda (/ ) ( le (lambda ( x ) ( (/ f ) x ))))))) Does (define . 1 72 Chapter 9 . That 's easy.. . Read this chapter just one more time and you will. ( (lambda ( le ) ((lambda ( mklength) ( mklength mklength) ) (lambda ( mklength) ( le (lambda ( x ) ( ( mklength mklength) x )))))) (lambda ( length) (lambda (l) (cond ( ( null? l) 0) (else ( add1 ( length ( cdr l )))))))) What did we actually get back? Let 's separate the function that makes length from the function that looks like length We extracted the original function mklength... (lambda ( le) ((lambda ( mklength) ( mklength mklength) ) (lambda ( mklength) ( le (lambda ( x ) ( ( mklength mklength) x )))))) Does this function have a name? Yes.. it is called the applicativeorder Y combinator. . now that we know what recursion is. . ) work again? Do you now know why Y works? Sure.Is this the right function? Yes...
and Again. and Again. Does your hat still fit? Perhaps not after such a mind stretcher. 173 . . and Again. . Leslie Bricusse and Anthony Newley . Stop the World/ Want to Get Off.What is ( Y Y) Who knows. . . but it works very hard. .
:[].(® €:) � &5 � W� � J�SJID � tij Cl1i00� � .
the two lists must be of equal length. Also. Make up some examples for entries. Here are our examples: ( (appetizer entree beverage) ( pate boeuf vi n ) ) and ( (appetizer entree beverage) ( beer beer beer) ) and ( (beverage dessert) ( (food is) ( n u m ber one with us) ) ) . How can we accomplish this? lookupinentry takes an additional argument that is invoked when name is not found in the first list of an entry. Why? How many arguments do you think this extra function should take? What Is the Value of All of This ? 1 75 . What is ( lookupinentry name entry) where name is entree and entry is ((a ppetizer entree beverage) (food tastes good ) ) What i f name i s dessert In this case we would like to leave the decision about what to do with the user of lookupinentry.An entry is a pair of lists whose first list is a set. We think it should take one. tastes. name. How can we build an entry from a set of names and a list of values? (define newentry build ) Try to build our examples with this function.
. What is ( lookupintable name table tablef ) where name is entree table is ( ( ( entree dessert ) ( spaghetti spu moni )) ( ( appetizer entree beverage ) ( food tastes good ) ) ) and table/ i s ( lambda ( name) . ) ( define extendtable cons) It could be either spaghetti or tastes. So it is spaghetti . Define the function extendtable which takes an entry and a table ( possibly the empty one ) and creates a new table by putting the new entry in front of the old table. Here is one example: the empty table. 176 Chapter 10 . Here is another one: ((( appetizer entree beverage ) ( pate boeuf vin )) (( beverage dessert ) ((food is ) ( n u m ber one with us )))) . but lookupintable searches the list of entries in order.Here is our definition of lookupinentry (define lookupinentry (lambda ( name entry entryf) ( lookupinentryhelp name (first entry) (second entry) entryf))) Finish the function lookupinentryhelp (define lookupinentryhelp (lambda ( name names values entryf) (cond (( null? names) ( entry/ name) ) ((eq ? ( car names) name) ( car values)) (else ( lookupinentryhelp name ( cdr names) ( cdr values) entryf))))) (define lookupinentryhelp (lambda ( name names values entryf ) (cond ) ( ( ) )))) ( A table ( also called an environment ) i s a list of entries. . represented by () Make up some others.
as to whether Did you notice that "sans serif" was not in sans serif? We hope so. Henceforth. Have we chosen a good representation for expressions? Yes. is the function that returns Do you remember value from chapter 6? Recall that value the natural value of expressions.Write lookupintable Hint : Don't forget to get some help. you must notice whether or not an atom is in sans serif. They are all Sexpressions so they can be data for functions . (lambda ( name) (lookupintable name ( cdr table} tablef)) In the preface we mentioned that sans serif typeface would be used to represent atoms. This is " a ns s serif' in sans serif. What kind of functions? For example. Remember to be very conscious or not a n atom is i n sans serif. To this point it has not mattered. What is the value of We don 't even know what (quote { a b c) ) is. ( car (quote {a b c) )) What Is the Value of All of This ? 1 77 . value. ( defi ne lookupintable (lambda (name table tablef ) ( c o nd (( null? table) ( table! name)) ( els e ( lookupinentry name ( car table} (lambda ( name) (lookupintable name ( cdr table} tablef))))))) Can you describe what the following function represents: This function i s the action to take when the name is not found in the first entry.
It is a representation of the expression: (car (quote (a b c))).What is the value of ( cons repa ( cons repb ( cons repc (quote ())))) where repa is a repb is b and repc is c Great . And what is the value of ( cons repcar ( cons ( cons repquote ( cons ( cons repa ( cons repb ( cons repc (quote ())))) (quote ()))) (quote ()))) where repcar is car repquote is quote repa is a repb is b and repc is c What is the value of ( car (quote (a b c) ) ) What i s ( value e ) where e is (car (q uote (a b c))) What is ( value e ) where e is (quote (car (quote (a b c) ))) It is the same as (a b c) . a. (car (q uote (a b c)) ) . a. 178 Chapter 10 .
What is the type of e where e is #f *const. *const. 6. ( (from nothing comes something) ) . nothing has no value. What Is the Value of All of This? 179 . because numbers are constants. What is ( value e) where e is ((lambda (nothing) (cond (nothing (q uote something)) (else (quote nothing)))) #t ) What is the type of where e is 6 e something.What is ( value e) where e is (addl 6 ) What is ( value e) where e is 6 What is ( value e) where e is (quote nothing) What is ( value e) where e is nothing What is ( value e) where e is ((lambda (nothing) (cons nothing (quote ()))) (quote (from nothing comes something) )) 7. nothing.
where e is nothing What is t he type of e where e is (lambda (x y) (cons *lambda. *identifier. *const. 180 Chapter 10 . *cond.What is { value e) where e is # f What is the type of e where e is cons What is ( value e) #f. x y)) What is the type of e where e is ((lambda (nothing) (cond (nothing (quote something)) (else (quote nothing) ))) #t ) What is the type of e where e is (cond (nothing (quote something)) (else (quote nothing))) *application. where e is car What is the type of e where e is {quote nothing) What is the type of e *quote. {primitive car) .
We call these functions "actions. They can be detected by an appropriate function to which Sexpressions are submitted before they are passed on to value. (lambda (car) car) . (cond (3 c) (else b) (6 a)). (lambda (#t) #t). atomtofunction useful when we rewrote value for numbered expresssions. We found . How do you think we should represent types? If actions are functions that do "the right thing" when applied to the appropriate type of expression. () . We choose functions." You guessed it. (lambda (5) 5). what should value do? Do you remember atomtofunction from chapter 8? Below is a function that produces the correct action ( or function ) for each possible Sexpression: (define expressiontoaction (lambda (e) (cond ( ( atom ? e) ( atomtoaction e)) (else (listtoaction e))))) Define the function atomtoaction 1 1 Illformed Sexpressions such as (quote a b). It would have to find out the type of expression it was passed and then use the associated action . and (1 2) are not considered here.How many types do you think there are? We found six: *const *quote *identifier *lambda *cond and *application. (lambda a). (define atomtoaction (lambda ( e) (cond (( number? e) *const) ( ( eq ? e #t ) *const) ( ( eq ? e #f ) *const) ( ( eq ? e (quote cons )) *const) ( ( eq ? e (quote car )) *const) ( ( eq ? e (quote cd r )) *const) ( ( eq ? e (quote null?)) *const) ( ( eq ? e (quote eq?)) *const) ( ( eq ? e (quote atom?)) *const) ( ( eq ? e (quote zero?) ) *const) ( ( eq ? e (quote add 1 ) ) *const) ( ( eq ? e (quote su b1)) *const) ( ( eq ? e (quote num ber?)) *const) (else *identifier)))) What Is the Value of All of This? 181 .
1 together with all the functions it uses. is called an interpreter. 1 Actions do speak louder than words . the expression e and a table. The function value.Now define the help function listtoaction (define listtoaction (lambda ( e ) (cond (( atom ? ( car e)) (cond ( ( eq ? ( car e) (quote quote )) *quote) ( ( eq ? ( car e) (quote lambda}) *lambda) ( ( eq ? ( car e) (quote cond}} *cond} (else *application))) (else *application)))) Assuming that expressiontoaction works. 182 Chapter 10 . we can use it to define value and meaning (define value (lambda ( e ) (meaning e (quote ())))) (define meaning (lambda ( e table) ( ( expressiontoaction e) e table))) What is (quote ()) in the definition of value It is the empty table. How many arguments should actions take according to the above? Two. The function value approximates the function eval available in Scheme (and Lisp ) .
(define textof second) (define *quote (lambda ( e table) ( textof e))) Define the help function textof Have we used the table yet? Why do we need the table? Given that the table contains the values of identifiers. For #f . For #t .Here is the action for constants. Why? (define initialtable (lambda ( name) ( car (quote ())))) When is it used? What is the value of (lambda (x ) x ) We don't know yet. but we will in a moment . . . but we know that it must be the representation of a nonprimitive function. What Is the Value of All of This ? 183 . (define *identifier (lambda ( e table) (lookupintable e table initialtable))) Here is initialtable Let's hope never. To remember the values of identifiers. . write the action *identifier No. it returns true. (define *const (lambda ( e table) ( co nd (( number? e) e) (( eq? e #t ) #t ) ((eq? e #f ) #f ) (else ( build (quote primitive) e))))) Is it correct? Here is the action for *quote Yes. 1 . it just returns the expression. and this is all we have to do for 0. it returns false. for numbers. 2. And all other atoms of constant type represent primitives.
e. . and the body). It is a special form that takes any number of condlines. In a list . Otherwise it proceeds to answer the right part . Write tableof formals. It considers each line in turn. At least. the table. And what else do we need to remember? We will also put the table in. nonprimitives are defined by their arguments and their function bodies. 184 Chapter 10 . If it sees an elseline. So when we want to use a nonprimitive we need to remember its formal arguments and its function body. the formal arguments. .How are nonprimitive functions different from primitives? We know what primitives do. just in case we might need it later. If the question part on the left is false. Fortunately this is just the cdr of a lam bda expression. ) in your own words.of and bodyof (nonpri mitive ( ( ( (y z) ( (8) 9 ) ) ) table (x) (cons x y ) )) �v� � � formals body (define tableof first) (define formalsof second) (define bodyof third ) Describe ( cond . And how do we represent this? Here is the action *lambda (define *lambda (lambda ( e table) ( build (quote nonpri m itive) ( cons table ( cdr e ) ) ) ) ) What i s ( meaning e table) where e is (lambda ( x ) (cons x y)) and table is (( (y z) ( (8) 9 ) ) ) I t i s probably a good idea t o define some help functions for getting back the parts in this three element list (i. . it looks at the rest of the lines. it treats that condline as if its question part were true. of course.
Do you understand *cond now? How can you become familiar with it? What Is the Value of All of This ? 185 .Here is the function evcon that does what we just said in words: (define evcon (lambda ( lines table ) (cond (( else? ( questionof ( car lines ) ) ) ( meaning ( answerof ( car lines ) ) table) ) (( meaning ( questionof ( car lines ) ) table) ( meaning ( answerof ( car lines ) ) table)) (else ( evcon ( cdr lines ) table ) ) ) ) ) Write else? and the help functions questionof and answerof Didn't we violate The First Commandment? (define else ? (lambda ( x ) (cond ( ( atom ? x ) ( eq ? (else # f ) ) ) ) x (quote else) ) ) (define questionof first) ( define answerof second) Yes. they make things quite a bit more readable. But you already knew that. A good one is: ( *cond e table) where e is (cond (coffee klatsch) (else party) ) and table is (( (coffee) ( #t ) ) ( ( klatsch party) (5 (6) ) ) ) . we don 't ask ( null ? lines ) . The best way is to try an example. Now use the function evcon to write the *cond action. ( define *cond (lambda ( e table) ( evcon ( condlinesof e) table ) ) ) ( define condlinesof cdr) Aren't these help functions useful? Yes. so one of the questions in every cond better be true. Perhaps not .
Have we seen how the table gets used? But how do the identifiers get into the table? Yes. Of course. . An application must always determine the meaning of all its arguments. functionof . ) (or . ) or (cond . Then we apply the meaning of the function to the meaning of the arguments. and argumentsof correctly. Yes. .of e) table) ( evlis ( argumentsof e) table)))) Is it correct? 1 86 Chapter 10 . do we have to get the meaning of all of its arguments? Write a function evlis that takes a list of (representations of) arguments and a table. and returns a list composed of the meaning of each argument . (define evlis (lambda ( args table) (cond ( ( null? args ) (quote ())) (else ( cons ( meaning ( car args ) table) ( evlis ( cdr args ) table)))))) What else do we need before we can determine the meaning of an application? And what then? We need to find out what its functionof means. ) Before we can apply a function. . . Here is *application (define *application (lambda ( e table) ( apply ( meaning (function. We just have to define apply. *lambda and *identifier use it . . like (and . An application is a list of expressions whose car position contains an expression whose value is a function . . In the only action we have not defined: *application . How is an application represented? How does an application differ from a special form.
(primitive primitivename) and (non. there i s n o answer. T h e function apply approximates the function apply available in Scheme ( and Lisp ) .pri mitive ( table formals body) ) The list ( table formals body) i s called a closure record. 1 What Is the Value of All of This ? 187 . Write primitive ? and nonprimitive ? (define primitive ? (lambda (l) ( eq ? (first l) (quote pri mitive) ) ) ) (define nonprimitive ? (lambda (l) ( eq ? (first l) (quote nonpri m itive) ) ) ) Now we can write the function apply Here i t is: ( define apply 1 (lambda (fun vals ) (cond ( (primitive ? fun) ( applyprimitive (second fun) vals ) ) ( ( nonprimitive ? fun) ( applyclosure (second fun) vals ) ) ) ) ) I f fu n does not evaluate to either a primitive o r a nonprimitive as in the expression ( ( l a m bda (x) (x 5 ) ) 3).Write functionof and argumentsof (define functionof car) (define argumentsof cdr) How many different kinds of functions are there? What are the two representations of functions? Two: primitives and nonprimitives.
5. 2. 188 Chapter 10 . 3. 4. cdr 1 eq ? (second vals ) :atom ? ( quote cons) ( define :atom ? (lambda ( x ) ( cond ( ( atom ? x ) #t ) ( ( null ? x ) #f ) ( ( eq ? ( car x ) ( quote prim itive) ) #t ) ( ( eq ? ( car x ) ( quote nonpri mitive)) #t ) ( else #f ) ) ) ) 1 of The function apply·primitive could check for applications cdr to the empty list or sub1 to 0. But we know what to do to find the meaning of (cons x y) where table is ( ( (x y) (1 (2) ) ) ) . 1. Here. and applyclosure must extend the table.This is the definition of applyprimitive (define applyprimitive (lambda ( name vals ) (cond (( eq ? name 1 ) ( cons (first vals ) (second vals ) ) ) ( ( eq ? name (quote car) ) ( car (first vals ) ) ) ( ( eq? name (quote cd r) ) ( 2 (first vals ) ) ) ( ( eq ? name (quote null?)) ( null ? (first vals ) ) ) ( ( eq ? name (quote eq?)) ( 3 (first vals ) 4 )) ( ( eq ? name (quote atom ?)) (first vals ) ) ) ( 5 ( ( eq ? name (quote zero?)) (zero ? (first vals ) ) ) ( ( eq ? name (quote add 1 ) ) ( add1 (first vals ) ) ) ( ( eq ? name (quote su b1)) (sub1 (first vals ) ) ) ( ( eq ? name (quote n u m ber?)) ( number? (first vals ) ) ) ) ) ) Fill i n the blanks. etc. That 's tricky. Is applyclosure the only function left ? How could we find the result of (f a b) where f is (lambda (x y) (cons x y)) a is 1 and b is (2) Why can we do this? Yes. we don 't need applyclosure .
Can you generalize the last two steps? Applying a nonprimitive functiona closureto a list of values is the same as finding the meaning of the closure's body with its table extended by an entry of the form (formals values ) In this entry. I n the following. The new e for meaning will b e ( cons z x ) and the new table for meaning will be ( ( (x y) ((a b c ) (d e f) ) ) What will be the new arguments of meaning ((u v w ) (1 2 3)) ( (x y z) (4 5 6))). closure is (((( u v w ) ( 1 2 3)) ( (x y z) (4 5 6) ) ) (x y) ( cons z x ) ) and vals is ( (a b c ) (d e f) ) . Have you followed all this? (define applyclosure (lambda ( closure vals ) ( meaning ( bodyof closure) ( extendtable ( newentry (formalsof closure) vals ) ( tableof closure ) ) ) ) ) This is a complicated function and it deserves an example. here is the definition of applyclosure . formals is the formals of the closure and values is the result of evlis . What Is the Value of All of This ? 189 . If not .
by using *identifier. because evlis returns a list of the meanings.What is the meaning of ( cons where z is 6 and x is (a b c ) z x ) The same as ( meaning e table) where e is ( cons z x) and table is ( ( (x y) ((a b c ) (d e f) )) ( ( u v w) ( 1 2 3)) ( (x y z ) (4 5 6) ) ) . we must find both ( meaning e table) where e is z and ( meaning e table) where e is x. cons . what is the result of evlis 6. Let 's find the meaning of all the arguments. What is ( meaning e table) where e is cons ( pri m itive ) by using *const. ( a b c ) . by using *identifier. 190 Chapter 10 . What is ( evlis args table) where args is ( z x) and table is ( ( (x y) ( (a b c) (d e f) ) ) ( ( u v w) ( 1 2 3)) ( (x y z ) (4 5 6) ) ) I n order t o d o this. (6 ( a b c )) . What i s the ( meaning e table) where e is z What is ( meaning e table) where e is x So.
. That may help a lot . . . don't botherwe can play the same game again. but see The Seasoned Schemer.We are now ready to ( apply fun vals ) where fun is ( pri mitive cons ) and vals is (6 (a b c )) Which path should we take? Which condline is chosen for ( applyprimitive name vals ) where name is cons and vals is (6 (a b c ) ) Are we finished now? But what about (define . Yes. we are exhausted. else What Is the Value of All of This ? 191 . Yes. The third: ( ( eq? name (quote cons )) ( cons (first vals ) (second vals ) ) ) . Yes. It isn't needed because recursion can be obtained from the Y combinator . Is (define . it 's time for a banquet . We would be able to define a function like lasttry ? that will show that we cannot define the new and improved willstop ?. ) The applyprimitive path. No. but don't bother. ) really not needed? Does that mean we can run the interpreter on the interpreter if we do the transformation with the Y combinator? What makes value unusual? Should willstop ? see representations of expressions? Does it help? It sees representations of expressions. . Yes.
.
At the end of The Seasoned Schemer you can find a set of references to Scheme and the reference to Common Lisp. respectively. Piet. Enjoy! Abbott. New York. 1957. Nagel. but only by way of telling an interesting story. Grooks. New York. London 1865 and 1872. Suppes. New York. Edwin A. To Mock a Mockingbird And Other Logic Puzzles Including an Amazing Adventure in Combinatory Logic. New York. 1884. Patrick. The Annotated Alice: Alice 's Adventures in Wonderland and Through the Looking Glass. 1958. 1985. Inc. New Jersey. go ahead and dive into the sequel.. There should be no confusion : these books are not here to prepare you to read the sequel. Raymond. Ernest and James R. What are your options? You could quickly run out and get the rest of the show. Take some time off and read some of these books instead. 1957. Some have nothing whatsoever to do with mathematics or logic. Knopf. All of these books are classics and some of them are quite old. Smullyan. Escher. Hein. Halmos. Inc. The MIT Press. or you could read some of the books that we mention below. Princeton . Potter. Inc . Litton Educational Publishers. Introduction to Logic. Douglas R. New York. Lewis.You've reached the intermission. when you have relaxed a bit . .) Carroll. Do not feel obliged to jump ahead to the next book. Cambridge. Alfred A. Newman . Godel 's Proof. Doubleday and Co. New York. Bach: an Eternal Golden Bmid. Ltd . 1952. . Hofstadter. 1960. Van Nostrand Co. .. Macmillan and Company. (Original publica tion: Seeley and Co. 1960. perhaps removed some of the calories that were foisted upon you. Original publications under different titles: Alice 's Adventures Under Ground and Through the Looking Glass and What Alice Found There. Inc. Gyorgy. Dover Publications. Intermission 193 . they are just for your entertainment. Clarkson M. . nevertheless they have stood the test of time and are all worthy of your notice. . Then. Godel. some have to do with mathematics.. New York. Paul R. London. Massachusetts. New York University Press. Introduction and notes by Martin Gardner. The Seasoned Schemer. 1979. and still others are just worth discovering. 1960. Flatland . P6lya. How to Solve It. Basic Books. Naive Set Theory.
.
1 1 5 intersectall . 158 lat ?. 108 61 x. 64 align . 145 evlis . 122 fun ?. 60. 140 lasttry. 185 even ?. 1 20 functionof . 109 latestfriend . 78 eqlist ?. 82 insertRf . 1 86 expressiontoaction . 132 insertL * . 1 1 7 edd1 . 106 2ndsubexp . 1 28 eq ?tuna. 73 ???. 116 intersect?. 1 52 allnums . 74 75 eq ?c . 132 insertR *. 1 76 first. 78 answerof . 184 build . 1 32 insertL. 183 + . 184 *quote . 1 84 fullfun ?. 181 atomtofunction. 43. 1 19 C. 1 89 applyprimitive. 1 1 7 keeplooking . 1 44 evensonly *fjco . 4850. 10 atomtoaction . 1 53 A. 59 addtup. 74 1stsubexp. 1 1 9 firsts . 46 formalsof . 19. 185 *const. 187 initialtable . 138 apair?. 86 insertLf . 160 length * . 108 else ?. 183 *identifier. 187 atom? . 151 evcon. 130 intersect . 185 cookies . 123 difference. 144 evensonly * . 134 bodyof . 44. 139 leftmost . 76. 130 insertR.Index *application. 5 1 . 93 eternity. 185 apply. 183 *lambda. 88 length . <. 187 applyclosure. 181 extendtable . 65 +. 1 14. 185 Index 195 . 188 argumentsof . =. 1 50 lastfriend . 105. 136 eqan ?. 186 *cond . 156 afriend . 1 18 add1 . =. 127 eq ?salad . 16. 73 74 > . 9 1 . 155 condlinesof . 106 t. 72. 1 1 5 equal ?. 94 eqset ?. 183 insertg. 92.
133 subst*. 185 rember. 99101 occur . 135. 1 76 lookupinentryhelp . 157 XXX . 146 third . 1 75 newfriend. 57. 85 subst2 . 141 multiinsertLR . 34. 114 subst. 81 rembereq?. 59 subset ?. 77 nonprimitive ?. 182 weight * . 129 remberf . 142. yyy . 102104. 152 shuffle . 5 1 . 187 numbered ?. 128. 122 seqL.listtoaction. 183 thelastfriend . 154 willstop ?. 136 multiremberf . 134. 56 . 141 multirember. 176 lookupintable. 117 Y. 135 multirember&co . 177 makeset . 1 13. 37. 131 seqrem . 184 textof . 121 second . 131 seqR . 141 multiinsertLR &co . 95 rember* . 52 tableof . 122 one ?. 120. 154 sub 1 . 76 primitive ?. 119 seconds . 87 member?. 149 lookupinentry. 139 nonums . 129 rempick . 187 questionof . 56. 133 sero ?. 106 pick . 112 meaning . 78 occur*. 53. 108 set ?. 106. 182 looking . 71 union. 116 value. 137 multisubst. 22 multiinsertL. 1 19 tup+ . 135 multiremberT . 41. 57 newentry. 94. 137 multirembereq ?. 108 196 Index . 182 member* . 126 . 79 operator. 69. 77. 133 seqS. 79 revpair. 85 onetoone ?. 143 multiinsertR. 121 revrel. 172 133 zub1 . 1 1 1 shift.