Table Of ContentLISP 1.5 Programmer's Manual
The Computation Center
and Research Laboratory of Electronics
Massachusetts Institutoef Technology
.John McCarthy
Paul W. Abrahams
Daniel .J. Edwards
Timothy P. Hart
Michael I.L evin
The M. IT.. Press 1111111
Massachusetts Institutoef Technology
Cambridge, Massachusetts
CopyrigMhatteedr ial
The ResearcLha boratoroyf Electroniisca sn interdepartmental
laboratoirnyw hichf acultmye mbersa nd graduatset udentfsr om
numerousa cademidce partmenctosn duct research.
The researcrhe porteidnt hidso cumenwt asm ade possibilnep art
by supporetx tendetdh eM assachusettIsn stituotfeT echnologRye,
searchL aboratoroyf Electronijcosi,ntl y by the U.S.A rmy, the
U.S.N avy (Office of NavalR esearch),a nd the U.S.A ir Force
(Office of ScientiRfiecs aerch) underC ontractD A36-039-sc-78108,
Departmenotf t he Army Task3 -99-25-001a-n0d8 i;n p artb y Con
tracDtA -SIG-36-039-61-aGdd1i4t;o inal supporwta s receivefdr om
theN ationaSlc iencFeo undatio(nG ranGt- 16526a)n d the Natinoal
InstituotfeH se alth( GrantM H-04737-02).
Reproductiionn w holeo r in parti sp ermitted fora ny purpose
oft he UniteSdt atesG overnment.
SECONDE DITION Fifteentphri nting, 1985
ISBN 206 21 30114 (paperback)
CopyrighMtaetde rial
PREFACE
The over-aldle signo ft he LISP ProgrammingS ystem ist hew ork ofJ ohnM cCarthy
andi sb asedo n hisp aper" RecursivFeu nctionosf S ymbolicE xpressionasn dT heirC om
putatiboyn M achine"w hich was publisheidn C ommunication2!s theA CM, April1 960.
Thism anual was writtebny Michael!.L evin.
The interpretwears programmed by StephenB . Russellan d DanielJ .E dward.s
The printa nd read programsw ere writtebny John McCa rthy,K limM aling,
DanielJ . Edwards,a ndP aulW . Abrahams.
The garbagec ollectoarn da rithmetifce aturewse re writtebny DanieJl. Edwards.
The compilre nad assemblerw ere writtebny TimothPy Harta nd Michael!L.e vin.
An earliecro mpilerw asw rittebny R oberBtr ayton.
The "LISP 1 Programmer'sM anual,M"a rch 1,1 960,wa s writtebny PhylliAs. Fox.
Additionaplr ogramsa nd suggestionwse re contributebdy thef ollowinmge m-
bers of theA rtificiIanlt elligenGcreo up of the ResearchL aboratoroyf E lectronics:
MarvinL . Minsky, BertramR aphaelL,o uisH odes, DavidM . R.P ark,D avidC .L uckham,
DanielG . Bobrow,J ames R. Slaglea,n d NathanieRlo chester.
August 1976,2 1
CopyrigMhatteedr ial
TABLE OF CONTENTS
I. THE LISP LANGUAGE
1.1 SymbolicE xpressions
1.2 Elementary Functions 2
1.3 ListN otation 4
1.4 The LISP Meta-language 5
1.5 SyntactiScu mmary 8
1.6 A Universal LISPF unction 10
II. THE LISP INTERPRETER SYSTEM 15
2.1 Variables 16
2.2 Constants 17
2.3 Functions 18
2.4 MachineL anguage Functions 18
2.5 Special Forms 18
2.6 Programmingf ort heI nterpreter 19
III. EXTENSION OF THE LISP LANGUAGE 20
3.1 Functional Arguments 20
3.2 Logical Connectisv e 21
3.3 Predicateasn d Truthi nL ISP 22
IV. ARITHMETIC IN LISP 24
4.1 Reading and Printing Numbers 24
4.2 Arithmetic Functianodn sP redicates 25
4.3 Programmingw ithA rithmetic 27
27
4.4 hTe Array Feature
V. THE PROGRAM FEATURE 29
31
VI. RUNNING THE LISP SYSTEM
31
6.1 Preparinag Card Deck
32
6.2 Tracing
32
6.3 rEror Diagnostics
6.4 The � Countearn de rrors et 34
v
CopyrigMhatteedri al
CONTENTS
VII. LISTS TRUCTURES 36
7.1 RepresentatoifoL ni stS tructure 36
7.2 ConstructioofnL istS tructure 38
7.3 PropertLyi sts 39
7.4 ListS tructurOep erators 41
7. 5T he Free- StoragLei stan d theG arbagCeo llector 42
VIII.A COMPLETE LISP PROGRAM - THE WANG ALGORITHM
FOR THE PROPOSITIONAL CALCULUS 44
APPENDIX A Functionasn dC onstants in het LISPS ystem 56
APPENDIX B The LISPI nterpreter 70
APPENDIX C The LISP AssemblyP rogram (LAP) 73
APPENDIX D The LISPC ompiler 76
APPENDIX E OVERLORD - The Monitor 80
APPENDIX F LISP Inpuatn dO utput 83
APPENDIX G MemoryA llocatianodn theG arbage Collector 89
APPENDIX H Recursioann dt he Push-Down List 91
APPENDIX I LISP forS HARE Distribution 93
INDEX TO FUNCTION DESCRIPTIONS 100
GLOSSARY 103
vi
CopyrigMhatteedr ial
THE LISPL ANGUAGE
1.
The LISP language isd esigned primarily fors ymbolicd atap rocessingI.t h as been
usedf ors ymbolic calculatioinnsd ifferentanida li ntegralc alculus.e lectriccailr cuit
theory.m athematicall ogic. game playinga.n do therf ieldosf a rtificiinatle lligenec.
LISPis af ormalm athematicallan guage. Iti s therefeo rpossiblteo g ive a con
cisey etc ompleet descriptoin ofi t. Such is thep urposeo ft hisfi rst sectiono f the
manual. Other sectionwsi lld escribe ways ofu sing LISP toa dvantage andw ille xplain
extensionosf t hel ang uage whichm ake ita convenienprto gram ming system.
LISPd ifferfsr om most programming languages int hreei mportanwta ys. The
firswta y is int he natureo ft he data. Int heL ISPlan guage.a lld ata arei nt hef orm
of symbolice xpressionuss ualyl refererd toa s S-expressionsS.- expressions areo f
indefinite length and have a branching treet ypeo fs tructureso. thats ignificatn sub
expressioncsa n be readily isolatIendt h.e L ISPp rogramming systetmh,e bulko f
availablmee mory is used fors toring S-expressions in the form of lists tructures.
This type of memory organization freest he programmer from then ecessitoyf
alolcating storagfeo rt he differenste ctionosf h isp rogram.
The secondim portan t part of theL ISPla nguagei st hes ourcela nguage itselwfh ich
specifieins whatw ay theS -expressioanrse to be rpocessed. Thisc onsistosf r ecur
sivef unctoins ofS -expressions. Sincet hen otatiofno rt hew riting ofr ecursive func
tions ofS -expressionsi si tselofu tsidteh eS -expression notaiton. itw illb e calledt he
meta language. Thesee xpressions willt hereforbee calledM -expressions.
ThirdL,I SPc ani nterparnedte xecuptreo grawmrsi ttiennt he form of S
expressionsT.h us, likmea chinel anguagea,n du nlikme osto ther highleerv ella nguages,
itc anb e used to generatep rogramsf orf urtheerx ecution.
1.1 ySmbolic Expressions
The most elementary typeo fS -expressioni st hea tomisycm bol.
DefinitioAnn: atomics ymboli sa strnig ofn o more thant hirty numeralsa ndc apital
letterst;h ef irscth aractemru stb e a letter.
Examples
A
APPLE
PART2
EXTRALONGSTRINGOFLETTERS
A4B66XYZ2
These symbolsa re calleadt omicb ecauset heya ret akena s a wholea nd aren ot
capableo fb eings pliwt ithin LISPi ntoi ndiviuadl characters. ThusA , B, and AB
haven o relatiotno each othere xcepti n so fara s theya re three distincatt omic
symbols.
All S-expressionasr e builto ut of atomic symbolsa nd the punctutaionm arks
CopyrigMhatteedr ial
I(I " . ")" , an d II II Theb asic operatfioorfn o mringS- expressioinsst oc ombinet wo
oft hem top roduce al argoenre .F romt het woa tomics ymbols A 1 and A2,o ne can
form theS -express(iAonI .A2 ).
DefinitioAnn: S -experssioins e itheanr atomic symboorl i ti s composedo ft hese
elements int he following order: leaf pta renthesis, an S-expression, dao t, an S
expressiona,n da righpta renthesis.
Noticteh att hisde finition isr ecursive.
Examples
ATOM
(A. B)
(A (Be ))
, .
((AIA.2 ) B)
.
«U . V) (X.Y ))
«U . V). (X. ( Y Zll)
I.2 ElementaryF unctions
We shaliln troduce some elementarfyun ctiosn ofS -expressionTso.d istinguish
thef unctions fromt heS -expressthiemosneslv es, we shallw ritefu nction nameisn
lowerc ase lettesrinsc,ea tomic symbolsc onsisotf o nluypp er casel ette.r sFurther
more, thea rgumenoft fsun ctoins willb eg rouped ins quareb rackets rathert han
parentheses. As a separatoorr punctuation mark we shall use the semicolon.
The firstfu nctiotnh atw e shalli ntroducies thefu nction� . Ith as twoa rgu
mentsa nd is inf act thef unctiotnh ati su sedt ob uildS -expressionfsr om smallSe·r
expressions.
Examples
cons(A;B]B=)( A
.
con[s(AB );e]=((A . B). e )
cons[cons[A;B.]B ;)e e])= «A
Thel ast exampilsea n instanceo f composition off unctions. Iti sp ossiblteob uild
any S-expression fromi tsa tomic componentbsy compositoifot hnesf u nction £Q!l§ .
Then expta iorf fu nctions do justt he opposiotfe� . Theyp roduce thes ubeprxes
sionosfa given expressino.
Thef unction �h as one argument. Itvsa lue ist he firpsatr to fi tsc omposiet
argument.c aro fan atomics ymboli su ndefined.
Examples
car[A( .B )]=A
car[.(( AB B2))A] =
1 .
car[«Al A.2 ) .B )]=(.AA l2 )
carrA]i su ndefined
2
CopyrighMtaetde rial
Thef unctcidohran s o near gument. Itsv aliust ehe s econdp arto fi tcso mposite
argumentc.dr i sa lsou ndefined ifi tsa rgumiesan tto mlc.
Exam ples
cdrlB(A) j=B
.
cdr[A( .( B.lB 2)=B)(lj B2)
cdr{((Al A.2. )B )j=B
cdrliAsuj n defined
carlcd(rl[B( BA.2 )=)Blj j
.
carlcdr[(A B)]is]u ndefined
rc ons;[B]=A jA
car
GivenS -expresisti poni, top roduce ofi t
any is ossble anys ubexpression by a
suitcaobmlpeo soif�t' is oann cdd r's.I fx andL repreasnetynw tSo - expressions,
thfeo llowiidnegn tairtteir ees
u :
ca[rco[n;xsJyl =x
cdr[cons[x;y]]=y
Thefo llowiidnegn itsia lstoyt rufeo arny S -expresxs siuocnht haxt i sc omposite
(noant-omic):
con[sc laxJ r ; cxJd =Jrx[
Thesy mbols2:. and L used inth ese identitiaerse c allvaeridab les.I nL ISPv,a r
iableas reu sedt or epreSs-eenxtp resIsnci hoonossn.ia nmgef sov ra riaabnldfe unsc
tionwse,s hall usteh seam et ypeo fc harasctritnges trha ta er used nif orming atomic
symbols,e xcpetth atw es hall usel owerc asel etters.
Af unction whosvea liusee i thterruo erf a lsei sc allea drpe dcaite. InL ISPt,h e
valuest ruean d � arreep resnetedb yt haet omsiymcb olsT andF , respectively.
AL ISPp redicaties t hereforae f uncwthioosvneal uiese itheTr o r F.
Thep rediecqia sta tese tf oerq uaolniat tomyic s ymbols. It isu ndefinedf or
nona-tomica rguments.
Examples
e[AA]=T
q ;
eq[AJ;=BF
eq[A.B; )(ilAsu ndefined
eq[(BA) ;.(B A)i]su ndefined
The predciate � .•[.' truiefit sa rgumenti sa n atomics ymbol.an d false ifi ts
argumenti sc omposite.
Examples
atomlE XTRALONGSTRINGOFLEJ=TTT ERS
atom [(U. V )] =F
atom[caVr)[J(JU:; T
.
3
CopyrigMhatteedr ial
ListN otation
1. 3
TheS -expresstihoahntas vbee euns ehde reorteoh favbee ewnr ititnde onnt ot atino
.
Iit su suamlorley tob ea blteo w rilties otfes x pressoifoi ndnse finitel ength.
convenient
sucahs( AB CD E).
AnyS -exprecsabsneie x opnr esisnte de rmofst hed onto tatHioowne.v LeIrS.hP as an
alternaitvef ormo fS- expressionc alltehldei nsottati 0r:. Thlei (smt 1 m 2 " . nm)c anb e
definientd e rmosf d onto tatiIotins .i d entcailt o{m l .{ m2 . {. .. .( mn .N IL..).» ).
Thea tomics ymbNoIlLs ervaesas t erminaftoolrisr ts Then ullli( s ti) si den
.
tcialto N ILL.i smtasyh avse ubliTshteds o.nto t ation antdh lei nsott amtaiybo en
useidn t hes ameS -expression.
Historitchseae lplayr.fa oterol re meonflt iss wtasst h ec omma(. );h owevetrh.e
blakni sn owge neralylu sedT.h et wo aree ntrielye quivalenti nL ISP(.A B.. C )i s
identitco(a ABl C ).
Examples
(AB C)=(.(A B . (C. NIL»))
«A B)C )=A( . (B. N IL.»( C. NIL»
(A B (CD »)=. ((BA . « C.( D. N IL». )N IL»)
(A)=.N( IAL )
«A»=«(AN IL.N) I L)
.
(A( B. C »=(A. ( B.C ). NIL»
Iti si mporttoba encto mfaem iliart hrees ultso fe lemeanrytf unctoino ns
with
S-expressioinnliss t n otationc.a anl wabyeds e termbiytnr eadn slating
written These
indtoton otation.
Exampels
car[B(C »A)A =
cdr[B( CA) ]=C() B
cons([BAC ;» )=B(C A)
car[«A BC)) J=B()A
cdr[(A»)=NIL
calrcd r[(AB C ))]=B
Iti sco nvenientto a bbrevimautlet i�p'lse ancdd r'sT.h iis sdo ne by forming
funcntaimoentsha tb egwiint ch,e ndw itrh ,a nhda vsee vear'aasln dd 'sb ewteen
them.
Examples
cadrB[C (»A) =carB(cC d)rJl=(BA
cadd[(Ar BC )J=C
cadad(rCB[)( D A» )=C
4
CopyrigMhatteedr ial
The lasta ord int hen ame actuallsyig niifes thefi rsotp eratioinn o rdetro b e
performeds, ince iti sn earestt ot hea rgument.
1.4T he LISP Meta-language
We havei ntroducedt yap eo fd atac alleSd- expressions,a ndf ivee lementray func
tionosfS -expressionsW.e havea lsod iscussetdh efo llowifneagt ures oft hem eta
language.
l. Function namesa ndv ariabnlaem es arel ikaeto mics ymbolse xceptt hatt hey
use lowerc asel etters.
z. The argumentso fa functioanr eb oundb y squareb racketasn ds eparatefdr om
eacho therb y semicolons.
3. Compositions off unctiomnasy bew rittbeyn u singn estedse ts ofb rackets.
Theser ulesa lloowne t ow ritef unctiodne finiiotnss ucha s
thir[xd]::ca[rcd r[cdr[x]]. ]
Thisf unctiosne lecttsh et ihrdi temo n a list.F ore xample,
thirBd C[D ()JA:: C
thirdi sa ctualltyh es ame functioans caddr.
The clasosf f unctitohantcs a nb e formedi nt hisw ay isq uite limiatneddn otv ery
interestinAg .m uch laregr classo ff unctiocnas nb e definebdy means oft hec on
ditioenxaprle ssiona,d evicfeo rp rovidinbrga nchesi nfu nction definitions.
A conditioneaxlp ressiohna st hef ollowing form:
wheree ach Pi isa n expressiownh osev aluem ay bet ruth orf alsitayn,d e ach ei is
any expression. The meaning ofa conditionaelx pressioins :i fP I ist rue,t hent he
valeu of el ist hev alueo ft hee ntireex pressi.o nIf PI isfa lse. theni fP z ist rue
thev alueo fe Z ist hev alueo ft hee ntireex pression. The Pi ares earchedf roml eft
tor ightu ntitlh ef irsttr ueo ne isf ound.T hent hec orrespondienig i ss electedI.f
noneo ft hep .a re true, thent hev alueo ft hee ntirexep ression isu ndefined.
1
Each p.o re . cani tseblefe ithear n S-expreas fusnictoionn,, a composiiton of
1 1
funtcionso r may itselbfe anothecro nditioneaxplr ession.
Example
[eq[ca r[x];A]-cons[B ;cd[rx];]T -x]
The atomics ymbol T represnetst ruth.T he valueo ft hise xpressioins o btained
if oner eplacesc aro f x byB if ihtap penst obe A .b utl eanvgix unc han ged if� of
iti sn ot A.
5
Copyrighted Material