The Little Schemer F
o
u
r
t h
E
d
i
t
i
o
n
Daniel P Friedman and Matthias Felleisen oreord bf G J. s
T Fis Commm When recurrng on a lst of atoms, la, k two questions about it: null la and s When recurring on a number, n, k two uestions about it: z n and s When recurrng on a lst of S-xpressons, l, k three uestion about it null l, am ca l, and s
T So Commm Use to build lists.
T Ti Commm When building a list, describe the rst typical element, an then cn it onto the natu ral recursion.
T Fou Commm Always cange at let one argument while recurrng. When recurrn recurrn on a lst lst of atoms, recurrng ng on on a num num la, us cdla. cdla. When recurr br, n, use u n. And when recurrig on a list of S-expressons, l, use cal and cd l f nither null nor am cal ae true. It must e chaged to b closer to termin ton. The changing argument must be tsted in the termination condtion: when usg cd, test trmination wth null and when sing u, test termnaton with
z.
T Fi Commm When buldng a value wih + ,lways se 0 for the value of the termining line, fo addng 0 does not change the value of a addition. When buldng a value wth always se 1 for the value of the teminti lie, fo multplyn by 1 does not change the value of a multiplication. When build a value wih lwy consider for the value of e emii line
T Si Commm Simplify only ter the function is oec
T Sv Commm Recur on the a that ae o e same nature: On the sublists of a list O the subexpressios of a ihmei expresson.
T ig Commm s help functions to abstact fom repesen tations.
T Ni Commm Abstract common patters with a ew fn ton.
T T Commm Build fuctons to collect moe th oe value at a time.
T Fis Commm When recurrng on a lst of atoms, la, k two questions about it: null la and s When recurring on a number, n, k two uestions about it: z n and s When recurrng on a lst of S-xpressons, l, k three uestion about it null l, am ca l, and s
T So Commm Use to build lists.
T Ti Commm When building a list, describe the rst typical element, an then cn it onto the natu ral recursion.
T Fou Commm Always cange at let one argument while recurrng. When recurrn recurrn on a lst lst of atoms, recurrng ng on on a num num la, us cdla. cdla. When recurr br, n, use u n. And when recurrig on a list of S-expressons, l, use cal and cd l f nither null nor am cal ae true. It must e chaged to b closer to termin ton. The changing argument must be tsted in the termination condtion: when usg cd, test trmination wth null and when sing u, test termnaton with
z.
T Fi Commm When buldng a value wih + ,lways se 0 for the value of the termining line, fo addng 0 does not change the value of a addition. When buldng a value wth always se 1 for the value of the teminti lie, fo multplyn by 1 does not change the value of a multiplication. When build a value wih lwy consider for the value of e emii line
T Si Commm Simplify only ter the function is oec
T Sv Commm Recur on the a that ae o e same nature: On the sublists of a list O the subexpressios of a ihmei expresson.
T ig Commm s help functions to abstact fom repesen tations.
T Ni Commm Abstract common patters with a ew fn ton.
T T Commm Build fuctons to collect moe th oe value at a time.
v R
T Lw o C he pimitive empty lists.
ca
is dened onl or on
T Lw o C he primitive cd cd is dened only o non empty lists. he cdo any non-empt list i always another list.
T Lw o Cos he primitive cn takes two arguments. he second argument to cn must be a list. he result is a list.
T Lw o Nu? he primitive nll s dened only or lists.
T Lw o q? he primitive ' takes to arguments. E must be a non-numerc atom.
T L Sc F E
Daniel P. Friedman Iaa U Boogo aa
Matthias Felleis R U Hoo Txa
Dg b D Bbb b G
Th MIT P Cbid M London Ennd
Origina edition pubished as e Little LISer © 19, 1974 by Scientic Research Associates irst MIT Press Edition, 197 © 199 Massachusetts Institute of Technoogy A rights resered No part of this book may be reproduce in any form by any eectronic or mechanica means (incuding photocopying, recording, or information storage and retriea) without permission in writing from the pubisher This book was set by the authors and was printed and bound in the United States of America Library of Congress Cataoging-in-Publication Data iedman, Danie P The litte schemer Danie P iedman and Matthias eleisen rawings by Duane Bibby foreword by Gera J Sussman4 e , 1st MIT Press ed p m Re ed of: The itte LISPer 3rd ed @199 Incudes ine. ISBN 0-22-5099-2 (pbk: ak paper) 1 Scheme (Computer program anguage) 2 LISP (Computer program language) I elleisen, Matthias II iedman, Daniel P Little LISPer III Tite 199 QA773S3475 005133dc20 95-3953 CIP
To Ma Helga and our childn
( C (Foreword ) (Preface ) T o ys) 2 Do It, Do It Again, and Again, and Again 3 Cons the Magnicent) 4 Numbers Games) 5 *Oh M y Gawd*: It's ll of Strs) 6 Shadows) 7 iends and Relations) 8 Lambda the Ultimate) 9 and Again, and Again, and Again, 0 What Is the Value of All of T his?) (Intermission (Index
Frer This foreword appered n the second nd thrd edos o The e Ser We reprnt t here with the permission of the uor In 197 I ook n inroductory course n photography Most o he studens includng e) ae into that ourse hoping to ear how to be creatveo te pctures ie the ones dred by rtists such Edward Weston. On the rst da the teche paenl explaned the long s of technica skls that he w going to teach us during the ter ey was nsel dam s "Zone System for pevsualzng the print values bacness in the nal prnt) in photograph and how they derve from the light intensities in the scene n support o his sil we had to learn the use of exposure meters to measure light intensities nd the use of exposure ime d deveopment tme to control the black level and the contrast in he imge. Ths is in turn supported by even lower level sklls such as loading lm developng nd printing and ixing chemicals One must learn to rituaize the process of developing sensitive materal so that one gets onsstent esults over many years of work. The rst laborator session ws devoted to ndng ou that developer feels sipper and tha xer smells awful But wht about creative composition? n order to be creatve one ust rs gin cotrol of the medium One an not even begin to thin about orgazing a geat photogph wthout havng the sills to mae t happen In engneerng, as n other creative arts , we ust lean to do anaysis to support our eorts in snthesis One cannot buld a beautiul and functonal brdge without a knowledge of steel and dirt and considerable matheatca tehnue o using this nowledge to compute the propertes of structures Simlarly, one annot build a beautiul computer system without a deep undersandng of how to "pevisualize he process generated by the procedures one wrtes Some photographers choose to use blac-and-white 810 plates while others hoose 35m sldes Each has its advantages and disadvantages Lie photgraphy, programming eures a hoice of medum. Lisp is the medium of choice for people who enoy free stle and exbilt Lisp was intially conceived as a theoretcal vehle fo ecurson theor and o symbolc algebr t has deveoped into uniuely powerul and exble family o software development tools poviding wrap-aound support for the pid-prototping of softwae sstems s wh other languages Lsp provides the glue for usng a vt libry o canned parts produced by members of the user communty n Lisp, procedures ae rs-class data, o be passed as arguments returned values, and stored in data structures Ths exibilit s vauable, but most mportantly t provides mechanisms for formalizng namng, and savig the idosthe ommon patterns of usage that are essental to engineeing design n addition, Lsp progrms can easly manpulate the representations of Lsp programsa feature that has encouraged the development of a vst structure of program synhesis and analss tools, such as oss-referencers The le LISer is a uniue approach to developig the slls underlying reative program ming in Lisp It painlessly pacages, wth considerable wit much of the drll and pratice that is necessary to learn the skills of onstructing recursve processe and anipulating ecursve daa-strutures. or the student of Lsp pogramming, The Lle Ser a pero the same servie that Hanon's nger exercses or Czerny's piano studies perform or the student o piano. Geald J ussan Cambidge, Massachusets
Foreor
ix
Prefe
To celebrate the twentieth anniersary of Scheme we reised Te Little LISer a third time, gae it the more accurate title The Little Sheer, and wrote a sequel: The Seasoned Sheer
Programs Programs accept accept data and produce data dat a Designing a program requires a thorough understa nd ing of of da daa a a good program reects the shape of the data it deals with Most collections of data, and hence most programs, are recursie. Recursion is the act of dening an obect or soling a problem in terms of itself The goal of this book is to teah the ader to tink ursiel Our rst task is to decide which langu language age to use to communicate this concept concept There are are three obious choices: a natural language, such English formal mathematics or a programming language Natur languages are ambiguous, imprecis im precise, e, and sometimes awkwardly erbose These are all irtues irt ues for general communication, but something of a drawback for communicating concisely as precise a concept recursion The language language of mathematics mathem atics is the opposite of natur language: language : it can epress powerful powerful formal ideas with only on ly a few few symbols symbol s Unfortunately, Unfortuna tely, the t he language of mathematic mathe maticss is oft often en ryptic and barely accessible accessible without special t raining The marriage of technology and mathematics mathematics presents us with a third , almost ideal choice: a programming programming language e beliee that programming languages are the best way to coney the concept of recursion They share with mathematics the ability to gie a form form eaning to a set of symbols symbol s But unlike unli ke mathematics, programming languages can be directly eperiencedyou can take the programs in this book, obsere their behaior, modify them, and eperience te eect of these modications Perhaps th e best programming programming language language for for teaching teaching recursion recursion i s Scheme Scheme is inherently symbolicthe symbolicthe prgrammer does not hae to think about t h e relaionship between the symbols of his own language language and the representations in the compu ter Recursion is Scheme' s nat ur ur computational computational mechanism the t he primary prima ry programming aciity is the creation of (potentially) (poten tially) recursie denitions Scheme implementations are predominantly interactethe progammer can immediately immediately participate participate in and obsere the behaior of of his programs And, An d, perhap mos importantly for ou 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 mathematical inclination. inclination . In fact, fact, he Little Seer is based on lecture notes om a two-week "quickie introduction to Scheme for students with no preious programming experience experience and an admitted admitted dislike for anything anything mathematical Many of of these students were pgras rsiel i See preparing prepa ring for for careers caree rs in public pu blic airs airs It is our o ur belief that writig pgras is essentially siple patte ogitio Since our only concern is recursie programing, our treatment is limited to t o the whys and wherefores wherefores of of ust a few few Scheme fea features tures:: car, cdr, cons, cons , eq? eq? , null?, zero?, zero?, add, sub, number?, and, o, quote, lambda, lambda, dene, dene, and cond cond Ideed, Ideed, our lnguage is an idealized Scheme The Little Sheer and The Seasoed Sheer will not introduce you to the practical world of programming, but a mastery of the concepts in these books proides a start toward understanding the nature of computation Prefae
i
What You Need to Know to Read This Boo The reader must be comfortble eading English, recognizing numbers, and ounting Acnowledgment We are indebted to many people for their contibutions and assistance throughout the devel opment of the second second and third edition of this book. book . We thank Bruce Bruce Duba, Duba , Kent Dybvig, Chri Haynes, Eugene Kohlbecer, Kohlbecer, Richard Richard Sa S alter, George Springer, Springer, Mitch Wa Wand, and Dvid Dvid S Wise or or countless discussion th at inuenced our thinking while onceiving this book Ghsan Abbas, Abbas , Charles Baer, David Boyer, Mie Dunn , Terry Falkenberg, Falkenberg, Rob Rob iedman, John Jo hn ateley, ateley, Mayer Goldberg, Iqbal Khan, Julia Lawal, Jon Mendelsohn, John Nienart, Jerey D Perotti, Ed Robertson, Anne Shpunto, Erich Smythe, Guy Steele, Todd Stein, nd Lary Weiselberg provided many important comments on th e drfts o o the boo We especially especially want want to than Bob Filman for being such a thorough and uncompromising critic through several reding Finally we wish to acknowledge Nancy Garrett, Peg Fletcher, and Bob Filman or contributing to the design and ery The fourth fourth and latest edition greatly beneted from Dorai Dorai Sitaram' s incredibly clever Scheme Scheme typesetting program ST Kent Dybvig's Chez Scheme made programming in Scheme a mot pleasant experience e gratefully acnowledge criticsms and suggestions fom Shelaswau Buhnell, Richard Cobbe, David Combs, Peter Drake, Kent Dybvig, Rob iedman, Steve Ganz, Chris Hayne, Erik Hilsdale, Eugene Kohlbecer, Shriram Krishnamurthi, Julia Lawall, Suzanne Menzel Collin McCurdy, John Nienart, Jon Rossie, Jonathan Sobel, eorge Springer, Guy Steele, John David Stone, Viram Subramaniam, Mitch Wnd, and Melissa Wingard-Phillips Guideine o the Reader Do not rush th rough thi book Read Read caref carefull ully; y; valuable valuable hints are are scattere scatteredd throughout th roughout the the text Do not read the book in fewer than three sittings Read ystematiclly f you do not lly understand one chapter, you will understand the next one even less The uestions are ordeed by increasing dicuty it will be hard to anwer later ones if you cnnot solve the earlier ones The book boo k is a dialogue between you and us about interesting interes ting examples of of Scheme progrms If you can can , try tr y the exampes exampes while you read Schemes are are readily readily ava available ilable Whie there are minor yntactic yntactic variations between between dierent implementations of Sheme (primarily t he spelling spe lling of particular names and the th e domain of pecic function function ) , Scheme is basiclly basiclly the same throughout the world To work with Scheme , you will need need to dene atom? subl and addl which we introdued in he Lttle Schemer (define atom? (bda x) (and (not (pair?
x))
(not (nu?
x)))))
To nd out whether your Scheme has the correct denition o atom? ty (atom? (quote ())) and make sure it etuns #f n act, the material i also suited or modern Lisps such Common Lisp To wor with Lisp, you will lso have to add the untion atom?: (defun atom? x) (not (istp x)))
xii
Preface
Moreover, Moreover, you may need to modify the programs slightly Typically, the material requires only a few canges Suggestions about how to try the programs in the t he book are provided provided in the ramenotes. amenotes preceded by "S: concern Scheme, those by "L: concern Common Lisp. add1 , sub1 sub1 , and zero? Since In chapter 4 we develop basic arithmetic arithmet ic from from three operators : add1 sub1 , you must dene them using the built-in primitives for Scheme does not provide add1 and sub1 addition and and subtraction subtr action Terefore Terefore,, to avoid a circularity, circula rity, our basic arithmet arith metic ic addition and subtrtion must be written using dierent symbols: + and , respectively We do not give give any formal denitions deni tions in this th is book bo ok We believe that you can form your own denitions and will thus remember them and understand them better than if we had written written eh one for you But be b e sure you know know and understand the Laws and Commandments thoroughly befor beforee assing assing te te by The key key to learning learning Scheme is "pattern recognition The Commadmets point out the patterns that you will have already seen Early in the book, book , some concets are narrowe narrowedd for for simpicity lter , they t hey are epanded epanded and qualied qualied You You should sh ould lso know that, while everything in the book is Scheme, Scheme itself is more general and incorporates incorporates more than we could coul d intelligibly cover 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 for diere dierent nt classes of symbols symbo ls Variables and and the th e names of primit pri mitive ive operations operatio ns are in ialc Bic data, including numbers and representations of truth and falsehood, is set in sans si Keywords, ie, dn, lambda, cond, l, and, o, and uo, are in boldac hen 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 typewrter face The typeface distinctions can be sfely ignored until chapter 10, where we treat programs as data inly, Webster denes "punctuation as the act of punctuating specically, the act, prtice, or system of usig standardized marks in writing and printing to separate sentences or sentence sentence elements elements or to make te te meaning clearer We have taken this denition literaly and have abadoed some familiar uses of punctuation in order to make the meaning clearer Specically, we have dropped the use of punctuation in the let-hand column whenever the item that precedes such punctuation is a term in our programming language Food appears in many of our examples for for two reasons reasons First Fir st , food food is easier to visualize visu alize than abstract abstract symbols (This is not a good good book to read while dieting ) We hope the choice of food will help you you understand the t he examples and concepts we we use Second, Second , we want to provide you with a little distraction distraction.. We know how how frustrating frustrating the subject matter m atter can be, and a little distraction will help y ou kee your sanity You You are now ready to start ood luck! e hope you will enjoy the challenges waiting for for you on the following pages Bon apptit! Daniel P. iedman Matthias Felleisen Felleisen
Preface
xiii
T L Sc
t true thi i atom? tom
Yes, because tom is a string of characters beginning with the letter
L (qute atm) o atm "L: and " ae decibed in the peface
it true tha thi is an atom? turke
Yes, because turke is a string of characters beginning with a letter.
i rue that his i an atom?
Yes, because 492 is a string of digits.
s it rue t hi is an atom? u
Yes, because u is a string o f one character, which is a lette.
s it ue tht thi i an atom? •bc$
Yes, becaue •abc$ is a string o f character begnning with a letter or special character other than a let ( or right parenthesis.
s it true tha ths is a list? (tom
Yes, beause (atom is an atom enclosed by parentheses.
492
L (qute (atm) ) o (atm)
it true ha this s list? (atom turke or
Tos
Yes, because it is a collection of atoms enclosed by parentheses.
3
ue or flse (lat? l) where l s (Jack prat coud eat no chicken at
ue, because each S-expresson n l s an atom
ue or false: (lat? l) where l s ((Jack prat ould eat no chicken at
False, snce (ar l) s a lst.
ue o r false (lat? l) where s (Jack (prat could eat no chickn at
False, snce one of the S-epressons n l s a lst.
ue or flse ( lat? l) where l s (
ue, because t does not contan a lt.
ue or false: a lat s a lst of atoms.
ue! Every lat s a lst of atoms!
Wrte the functon lat? usng some, but not necessrly all, of the follong functons: ar dr on nul atom? and eq?
You were not expected to be able to do ths yet, because you are stll mssng some ngredents. Go on to the next queston Good luck.
?
o I o I Aan an Aan an Aan
15
Is it true that this is a list? (
Yes, because it contains zero S-expression enclosed by parentheses. This special S-expresion is called the null (or empty) lit.
Is it true that this i an atom?
No, because ( is jut a list.
()
Is it true that this is list? (( ( ( (
Yes, because it is a collection of S-expressions enclosed by parentheses.
What i the of where is the argument (a b c
a,
What is the of where is ((a b c z
(a b c, because (a b c is t he rst S-expression of this non-empty list.
What is the of where is hotdog
No answer. You cannot k for the of an atom.
Wht is the of where is ()
No answer. You cannot k for the of the empty list.
because a is the rst atom of this list.
L nil
Th Lw f h pe n n nnp .
Tos
5
What is the car of l where is (((hotdogs (and (ick rish
( (hotdogs , read : "The lst of th e list of hds " ((hotdogs is the rst S-expression of l
What is (car l) where is (((hotdogs (and (ick rish
( (hotdogs , because (car l) is nother way to for "the car of the list l"
What is (car (car l)) where ((( hotdogs (and
(hotdos.
What i s the cdr of l where l is (a b c
(b c, because (b c is the list l without (car l)
Note "cdr is pronounced "could-er hat is the cdr of l where is ((a b c z
( z
Wht is the cdr of l where is (hamburgr
(
What is (cdr l) where l is (( t r
(t r, because (cdr l) is just another way to for "the cdr of the list l."
What is (cdr a) where a is hotdogs
No answer You cannot for the cdr of an atom.
Chaper
Wt cdr ) wr
o n. Yo nno o cdr o .
L
i
Th w f The primitive cdr is dened only for non-mpty lists. The cdr of any no emty list is always anothr list.
W car cdr )) wr s b ( ((
(
Wat s cdr cdr )) wr i b ( ((
(((
Wat cdr car )) w b ( d
o n in car ) n o nd cd r do no n o n gn T o Cd.
Wat dos car a an rgmn?
ny non-py
Wat do cdr n gn?
y on-py
Wat s t con o t o a nd i wr a i peanut and butter nd jell Ts can ao b wrin cons a ) Rd cons t ato a ono
peanut butter nd jell b con dd n o o on o
Tos
b (( (( cdr ) nd ( car o cdr ).
b (( (( cdr ) nd t cdr o cdr )
(((
7
What is the of and where i (banana and and is (peanut butter and j
((banana a nd peanut butter and , because add any S-expssion to the front of a list
What is ) where is ((help this and is (is ver ((hard to earn
(( (hel p this is ver (( hard to arn .
What does take its arguments?
taes two argument:
the rst one is any S-expression; the second one i any list What is ) where is ( ()) and is ()
((a b because () is a list
What is ) where is a and is ( )
(a) .
What is ) where is ((a b and is b
No anwer, since the second argument must be a list.
hat is ) where i a and is b
No answer. Why?
8
In pactice, cn wok fo a value an c cn = c cn } =
an
Chaper
Th Lw f ns he pe e wo aguen. he econ guen o u be a . he eu a .
hat is (cs s (ar l)) here is ad is ((b c d
hat is ( s s ( r l)) hee is and is ((b c d
c d
s i t true that the list l i s the null ist ere l is (
Yes, because it i s th e list composed of zero Sepressions This question can also be written
b hy?
hy?
(nll? l).
hat is ( l? (uo ( )
L:
Is l) true or false here l is (a b c
y
ue, because (uo () ) is a notation for the null list. L: Aso
a • S Also •
False, because l is a non-empty list.
9
s null? a) tue or false where a i spaghetti
No answer/ because you cannot as null? o atom
In pactice, null? ) i fae fo eveything, except the empy it
Th Lw f Nll he pe n s de ne only fo lsts.
it tue o ale that i an ato where is Harr
ue, becaue Harr is a string of haractes beginning with a letter
s atom ? true o lse where i Harr
ue, becaue atom? i just another way to "Is i an atom?
L (def atm? (x) (nt (li sp x) ) ) (define atm? (lda (x) (ad (nt (pai? x)) t (ull? x) ) ) ) )
s atom? true or ale where i Harr had a heap o apples
Flse, since is list
How any arguet doe atom? tae and what re they
t takes one argument The argument an be any S-expresion
10
Chaper
s (atom? (car l)) true or ale where l s (Harry had a hap o appls
ue, because (ar ) s Harry, and Harry s an aom.
s (atom? (cd l)) true or alse where l s (Harry had a heap o appes
False.
Is (atom? (cd l)) true or false where l s (Harry
False, becaue the lst ( s not an tom.
s (atom? (car (cdr l))) true or alse were l s (swing low sweet cherr oat
ue, because (cdr l) s (low sweet cherr oat , and (car (cdr l)) s low, whch s an atom.
Is (atom? (ar (cdr l))) true o r false where l s (swing (low sweet chrr oat
False, snce ( dr l) s ((low sweet cherr oat, nd (car (cdr l)) s (low sweet, whch s a lst
ue or false a1 and a2 are he same atom where a1 s Harry and a2 s Harry
ue, because a1 s he aom Harr and a2 s he atom Harr
Is ( eq? a1 a2) true or false where a1 s Harr nd a2 s Harry
ue, because (eq? a1 a2) s jus another way to , "re a1 and a2 the same non-numerc atom?
L e
s ( eq? a1 a2) true or se where a1 s margarine and a2 s butter
Fse, snce a1 and a2 are derent atoms.
11
How many arguments does eq ? take and what are they?
It takes two argument Both of them must be non-numeric atoms
Is ( eq? l1 l2) true or false where is and l2 is (srawbrry
No aswer, ) and (srawbrry are lits
i, ists m8 be aguments f q? T ists ae
q? if ty th sam ist
Is ( eq? n1 n2) true or false where n1 is 6 and n2 is
No answer, 6 and are numbers
te, sm umbs may be agums f q?
Th Lw f Eq? he pe eq ke wo guen. Ech u be a non nuec ato.
Is ( eq? ( r ) true or false where l is (Mar had a ie amb chop and is Mar
ue, because ( r ) is the atom May, and the argument is also the atom Mary
Is ( eq? ( cdr l) true or false where l is (sourd mik and is milk
No answer. See The Laws of Eq? and Cdr.
12
Chaper
Is ( eq? ( car l) ( car ( cdr l )) ) true or false where l is (bans bans w nd jy bans
ue because it compares the rst and second atoms in the list.
=No go k ou pu b n jll nwich. ¢
Tis space reserved or
JELLY STANS!
13
m �