Upload
phamxuyen
View
237
Download
1
Embed Size (px)
Citation preview
Introduc)ontoRacket,adialectofLISP:ExpressionsandDeclara)ons
CS251ProgrammingLanguagesSpring2018,LynTurbak
DepartmentofComputerScienceWellesleyCollege
TheseslidesbuildonBenWood’sFall‘15slides
LISP:designedbyJohnMcCarthy,1958published1960
2Expr/decl
LISP:implementedbySteveRussell,early1960s
3Expr/decl
LISP:LIStProcessing
• McCarthy,MITarNficialintelligence,1950s-60s– AdviceTaker:representlogicasdata,notjustprogram
• Neededalanguagefor:– SymboliccomputaNon– Programmingwithlogic– ArNficialintelligence– Experimentalprogramming
• Somakeone!
i.e.,notjustnumbercrunching
Emacs:M-xdoctor
4Expr/decl
Scheme• GeraldJaySussmanand
GuyLewisSteele(mid1970s)• Lexically-scopeddialectofLISP
thatarosefromtryingtomakean“actor”language.
• Describedinamazing“LambdatheUlNmate”papers(hap://library.readscheme.org/page1.html)– LambdatheUlNmatePLbloginspiredbythese:
hap://lambda-the-ulNmate.org
• LedtoStructureandInterpretaNonofComputerPrograms(SICP)andMIT6.001(haps://mitpress.mit.edu/sicp/)
5Expr/decl
• GrandchildofLISP(variantofScheme)– Somechanges/improvements,quitesimilar
• DevelopedbythePLTgroup(haps://racket-lang.org/people.html),thesamefolkswhocreatedDrJava.
• WhystudyRacketinCS251?– Cleanslate,unfamiliar– CarefulstudyofPLfoundaNons(“PLmindset”)– FuncNonalprogrammingparadigm
• EmphasisonfuncNonsandtheircomposiNon• Immutabledata(lists)
– Beautyofminimalism– Observedesignconstraints/historicalcontext
6Expr/decl
Expressions,Values,andDeclaraNons
• EnNrelanguage:thesethreethings
• Expressionshaveevalua6onrules:– Howtodeterminethevaluedenotedbyanexpression.
• Foreachstructureweaddtothelanguage:– Whatisitssyntax?Howisitwriaen?– Whatisitsevalua)onrule?Howisitevaluatedtoavalue(expressionthatcannotbeevaluatedfurther)?
7Expr/decl
Values
• Valuesareexpressionsthatcannotbeevaluatedfurther.
• Syntax:– Numbers:251, 240, 301– Booleans:#t, #f – Therearemorevalueswewillmeetsoon(strings,symbols,lists,funcNons,…)
• EvaluaNonrule:– Valuesevaluatetothemselves.
8Expr/decl
AddiNonexpression:syntax
Addstwonumberstogether. Syntax: (+ E1 E2)
Everyparenthesisrequired;nonemaybeomiaed.E1andE2 standinforanyexpression.NoteprefixnotaNon.
Examples:(+ 251 240) (+ (+ 251 240) 301) (+ #t 251)
Noterecursivestructure!
9Expr/decl
AddiNonexpression:evaluaNon
Syntax: (+ E1 E2) EvaluaNonrule:
1. EvaluateE1toavalueV12. EvaluateE2toavalueV23. ReturnthearithmeNcsumofV1 + V2.
Noterecursivestructure!
Notquite!10Expr/decl
AddiNon:dynamictypecheckingSyntax: (+ E1 E2)
EvaluaNonrule:1. evaluateE1toavalueV12. EvaluateE2toavalueV23. IfV1andV2arebothnumbersthen
returnthearithmeNcsumofV1 + V2.4. Otherwise,atypeerroroccurs.
Dynamictype-checking
S)llnotquite!Morelater…
11Expr/decl
EvaluaNonAsserNonsFormalizeEvaluaNon
Theevalua)onasser)onnotaNonE↓ Vmeans``EevaluatestoV’’.
OurevaluaNonrulessofar:
• valuerule:V↓ V(whereVisanumberorboolean)
• addi6onrule:ifE1↓ V1andE2↓ V2andV1andV2arebothnumbersandVisthesumofV1andV2then(+ E1 E2) ↓ V
12Expr/decl
EvaluaNonDerivaNoninEnglishAnevalua)onderiva)onisa``proof’’thatanexpressionevaluatestoavalueusingtheevaluaNonrules.(+ 3 (+ 5 4)) ↓ 12 bytheaddiNonrulebecause:
• 3 ↓ 3 bythevaluerule
• (+ 5 4) ↓ 9 bytheaddiNonrulebecause:
– 5 ↓ 5 bythevaluerule
– 4 ↓ 4 bythevaluerule
– 5and4arebothnumbers
– 9isthesumof5and4
• 3and9arebothnumbers
• 12isthesumof3and9
13Expr/decl
MoreCompactDerivaNonNotaNon
V↓ V
whereVisavalue(number,boolean,etc.)
[valuerule] E1↓ V1E2↓ V2(+ E1E2)↓ V
[addiNonrule]
WhereV1andV2arenumbersandVisthesumofV1andV2.
3 ↓ 3 [value]5 ↓ 5 [value] 4 ↓ 4 [value](+ 5 4)↓9 (+ 3 (+ 5 4))↓12
[addiNon]
sidecondiNonsofrules
[addiNon]
14Expr/decl
ErrorsAreModeledby“Stuck”DerivaNons
#t ↓ #t [value]5 ↓ 5 [value]
4 ↓ 4 [value]
(+ 5 4)↓9
[addiNon]
Stuckhere.Can’tapply(addiNon)rulebecause#tisnotanumberin(+#t9)
Howtoevaluate(+ #t (+ 5 4))?
Howtoevaluate(+ (+ 1 2) (+ 5 #f))?
1 ↓ 1 [value] 2 ↓ 2 [value]
(+ 1 2) ↓ 3 [addiNon]
5 ↓ 5 [value]
#f ↓ #f [value]
Stuckhere.Can’tapply(addiNon)rulebecause#fisnotanumberin(+5#f)
15Expr/decl
SyntacNcSugarforAddiNonTheaddiNonoperator+cantakeanynumberofoperands.
• Fornow,treat(+ E1 E2 … En)as(+ (+ E1 E2) … En) E.g.,treat(+ 7 2 -5 8)as(+ (+ (+ 7 2) -5) 8)
• Treat(+ E)asE(orsayifE↓Vthen(+ E)↓V)
• Treat(+)as0(orsay(+)↓ 0 )
• Thisapproachisknownassyntac)csugar:introducenewsyntacNcformsthat“desugar”intoexisNngones.
• Inthiscase,analternaNveapproachwouldbetointroducemorecomplexevaluaNonruleswhen+hasanumberofargumentsdifferentfrom2.
16Expr/decl
OtherArithmeNcOperatorsSimilarsyntaxandevaluaNonfor
- * / quotient remainder min max except:• Secondargumentof/,quotient,remainder
mustbenonzero• Resultof/isaraNonalnumber(fracNon)whenbothvaluesare
integers.(ItisafloaNngpointnumberifatleastonevalueisafloat.)
• quotientandremaindertakeexactlytwoarguments;anythingelseisanerror.
• (- E)istreatedas(- 0 E)• (/ E)istreatedas(/ 1 E)• (min E)and(max E)treatedasE• (*)evaluatesto1.• (/),(-),(min),(max)areerrors(i.e.,stuck)
17Expr/decl
RelaNonOperatorsThefollowingrelaNonaloperatorsonnumbersreturnbooleans:< <= = >= > Forexample:
E1↓ V1E2↓ V2(< E1E2)↓ V
[lessthan]
WhereV1andV2arenumbersandVis#tifV1islessthanV2or#fifV1isnotlessthanV2
18Expr/decl
CondiNonal(if)expressions
Syntax: (if Etest Ethen Eelse)EvaluaNonrule:
1. EvaluateEtest toavalueVtest.2. IfVtestisnotthevalue#fthen
returntheresultofevaluaNngEthenotherwise
returntheresultofevaluaNngEelse
19Expr/decl
DerivaNon-stylerulesforCondiNonals
Etest↓ VtestEthen↓ Vthen(if EtestEthenEelse)↓ Vthen
[ifnonfalse]
WhereVtestisnot#f
Etest↓ #f Eelse↓ Velse(if EtestEthenEelse)↓ Velse
[iffalse]
Eelseisnotevaluated!
Ethenisnotevaluated!
20Expr/decl
YourturnUseevaluaNonderivaNonstoevaluatethefollowingexpressions
(if (< 8 2) (+ #f 5) (+ 3 4))
(if (+ 1 2) (- 3 7) (/ 9 0))
(+ (if (< 1 2) (* 3 4) (/ 5 6)) 7)
(+ (if 1 2 3) #t)
21Expr/decl
Expressionsvs.statementsCondiNonalexpressionscangoanywhereanexpressionisexpected:
(+ 4 (* (if (< 9 (- 251 240)) 2 3) 5))
(if (if (< 1 2) (> 4 3) (> 5 6))
(+ 7 8)
(* 9 10)
Note:ifisanexpression,notastatement.DootherlanguagesyouknowhavecondiNonalexpressionsinaddiNontocondiNonalstatements?(Manydo!Java,JavaScript,Python,…)
22Expr/decl
CondiNonalexpressions:careful!
Unlikeearlierexpressions,notallsubexpressionsofifexpressionsareevaluated!(if (> 251 240) 251 (/ 251 0))
(if #f (+ #t 240) 251)
23Expr/decl
DesignchoiceincondiNonalsemanNcs
Etest↓ VtestEthen↓ Vthen
(if EtestEthenEelse)↓ Vthen
[ifnonfalse]
WhereVtestisnot#f
Inthe[ifnonfalse]rule,Vtestisnotrequiredtobeaboolean!
Etest↓ #tEthen↓ Vthen
(if EtestEthenEelse)↓ Vthen
Thisisadesignchoiceforthelanguagedesigner.Whatwouldhappenifwereplacetheaboveruleby
[iftrue]
ThisdesignchoiceisrelatedtonoNonsof“truthiness”and“falsiness”thatyouwillexploreinPS2.
24Expr/decl
Environments:MoNvaNonWanttobeabletonamevaluessocanrefertothemlaterbyname.E.g.;
(define x (+ 1 2))
(define y (* 4 x))
(define diff (- y x))
(define test (< x diff))
(if test (+ (* x y) diff) 17)
25Expr/decl
Environments:DefiniNon• AnenvironmentisasequenceofbindingsthatassociateidenNfiers(variablenames)withvalues.– Concreteexample:num ⟼ 17, absoluteZero ⟼ -273, true ⟼#t
– AbstractExample(useIdtorangeoveridenNfiers=names): Id1 ⟼ V1, Id2 ⟼ V2, …, Idn ⟼ Vn
– Emptyenvironment:∅• AnenvironmentservesasacontextforevaluaNngexpressionsthatcontainidenNfiers.
• SecondargumenttoevaluaNon,whichtakesbothanexpressionandanenvironment.
26Expr/decl
AddiNon:evaluaNonwithenvironment
Syntax: (+ E1 E2)
EvaluaNonrule:1. evaluateE1inthecurrentenvironmenttoavalueV12. EvaluateE2inthecurrentenvironmenttoavalueV23. IfV1andV2arebothnumbersthen
returnthearithmeNcsumofV1 + V2.4. Otherwise,atypeerroroccurs.
27Expr/decl
VariablereferencesSyntax:Id
Id:anyiden6fier
EvaluaNonrule:LookupandreturnthevaluetowhichIdisboundinthecurrentenvironment.
• Look-upproceedsbysearchingfromthemost-recentlyaddedbindingstotheleast-recentlyaddedbindings(fronttobackinourrepresentaNon)
• IfIdisnotboundinthecurrentenvironment,evaluaNngitis“stuck”atanunboundvariableerror.
Examples:• Supposeenvisnum ⟼ 17, absZero ⟼ -273, true ⟼ #t, num ⟼ 5
• Inenv,numevaluatesto17(morerecentthan5),absZeroevaluatesto-273, andtrueevaluatesto#t.Anyothernameisstuck.
28Expr/decl
defineDeclaraNonsSyntax:(define Id E)
define:keywordId:anyiden6fierE:anyexpression
Thisisadeclara)on,notanexpression!Wewillsayadeclara)onsareprocessed,notevaluated Processingrule:
1. EvaluateE toavalueV inthecurrentenvironment2. ProduceanewenvironmentthatisidenNcaltothe
currentenvironment,withtheaddiNonalbindingId→Vatthefront.Usethisnewenvironmentasthecurrentenvironmentgoingforward.
29Expr/decl
Environments:Exampleenv0=∅ (canwriteas.intext)
(define x (+ 1 2))
env1=x⟼ 3, ∅ (abbreviated x⟼ 3;canwriteasx -> 3intext)
(define y (* 4 x))
env2=y ⟼ 12, x ⟼ 3 (most recent binding 2irst) (define diff (- y x))
env3=diff ⟼ 9, y ⟼ 12, x ⟼ 3
(define test (< x diff))
env4=test ⟼ #t, diff ⟼ 9, y ⟼ 12, x ⟼ 3
(if test (+ (* x 5) diff) 17)
environmenthereissNllenv4(define x (* x y))
env5=x ⟼ 36, test ⟼ #t, diff ⟼ 9, y ⟼ 12, x ⟼ 3 Notethatbindingx ⟼ 36“shadows”x ⟼ 3,makingitinaccessible
30Expr/decl
EvaluaNonAsserNons&RuleswithEnvironments
V#env↓ V
whereVisavalue(number,boolean,etc.)
[value]
E1#env↓ V1E2#env↓ V2
(+ E1E2)#env↓ V
[addiNon]
WhereV1andV2arenumbersandVisthesumofV1andV2.RulesforotherarithmeNcandrelaNonalopsaresimilar.
Theevalua)onasser)onnotaNonE#env↓ Vmeans``EvaluaNngexpressionEinenvironmentenvyieldsvalueV’’.
Id#env↓ V
WhereIdisanidenNfierandId⟼ VisthefirstbindinginenvforId
[varref]
E1#env↓ V1E2#env↓ V2
(if E1E2E3)#env↓ V2
[ifnonfalse]
WhereV1isnot#f
E1#env↓ #f E3#env↓ V3
(if E1E2E3)#env↓ V3
[iffalse]
Onlythisruleactuallyusesenv;othersjustpassitalong
31Expr/decl
ExampleDerivaNonwithEnvironments
test #env4↓#t[varref] x#env4↓3[varref] 5#env4↓5[value] (* x 5)#env4↓15 diff#env4↓9[varref](+ (* x 5) diff)#env4↓24(if test (+ (* x 5) diff) 17)#env4↓24
Supposeenv4=test ⟼ #t, diff ⟼ 9, y ⟼ 12, x ⟼ 3
[mulNplicaNon]
[addiNon]
[ifnonfalse]
32Expr/decl
Conclusion-below-subderivaNons,intext
| test # env4 ↓ #t [varref] | | | x # env4 ↓ 3 [varref] | | | 5 # env4 ↓ 5 [value] | | -------------------- [multiplication]
| | (* x 5) # env4 ↓ 15 | | diff # env4 ↓ 9 [varref] | | ------------------------- [addition]
| (+ (* x 5) diff)# env4 ↓ 24 ---------------------------------------- [if nonfalse]
(if test (+ (* x 5) diff) 17)# env4 ↓ 24
Suppose env4 = test -> #t, diff -> 9, y -> 12, x -> 3
33Expr/decl
Conclusion-above-subderivaNons,withbullets
(if test (+ (* x 5) diff) 17)# env4 ↓ 24 [if nonfalse] q test # env4 ↓ #t [varref] q (+ (* x 5) diff)# env4 ↓ 24 [addition]
o (* x 5) # env4 ↓ 15 [multiplication] § x # env4 ↓ 3 [varref] § 5 # env4 ↓ 5 [value]
o diff # env4 ↓ 9 [multiplication]
Suppose env4 = test -> #t, diff -> 9, y -> 12, x -> 3
34Expr/decl
FormalizingdefiniNons
E # env ↓ V (define Id E)# env ⇓ Id ⟼ V, env
[define]
Thedeclara)onasser)onnotaNon(define Id E)#env⇓ env’means``ProcessingthedefiniNon(define Id E)inenvironmentenvyieldsanewenvironmentenv’’’.Weuseadifferentarrow,⇓, toemphasizethatdefiniNonsarenotevaluatedtovalues,butprocessedtoenvironments.
35Expr/decl
ThreadingenvironmentsthroughdefiniNons 2 # � ↓ 2 [value]
3 # � ↓ 3 [value]
(+ 2 3)# � ↓ 5
(define a (+ 2 3))# � ⇓ a ⟼ 5
[define]
[addiNon]
a # a ⟼ 5 ↓ 5 [varref]
a # a ⟼ 5 ↓ 5 [varref]
(* a a)# a ⟼ 5 ↓ 25
(define b (* a a))# a ⟼ 5 ⇓ b ⟼ 25, a ⟼ 5
[define]
[mulNplicaNon]
b # b ⟼ 25, a ⟼ 5 ↓ 25 [varref]
a # b ⟼ 25, a ⟼ 5 ↓ 5 [varref]
(- b a)# b ⟼ 25, a ⟼ 5 ↓ 20
[subtracNon]
36Expr/decl
RacketIdenNfiers• RacketidenNfiersarecasesensiNve.Thefollowingarefourdifferent
idenNfiers:ABC,Abc,aBc,abc • Unlikemostlanguages,RacketisveryliberalwithitsdefiniNonoflegal
idenNfers.PreaymuchanycharactersequenceisallowedasidenNfierwiththefollowingexcepNons:– Can’tcontainwhitespace– Can’tcontainspecialcharacters()[]{}”,’`;#|\ – Can’thavesamesyntaxasanumber
• Thismeansvariablenamescanuse(andevenbeginwith)digitsandcharacterslike!@$%^&*.-+_:<=>?/ E.g.:– myLongName, my_long__name, my-long-name– is_a+b<c*d-e? – 76Trombones
• WhyareotherlanguageslessliberalwithlegalidenNfiers?
37Expr/decl
Small-stepvs.big-stepsemanNcsTheevaluaNonderivaNonswe’veseensofararecalledabig-stepseman)csbecausethederivaNone#env2↓vexplainstheevaluaNonofetovasone“bigstep”jusNfiedbytheevaluaNonofitssubexpressions.
AnalternaNvewaytoexpressevaluaNonisasmall-stepseman)csinwhichanexpressionissimplifiedtoavalueinasequenceofstepsthatsimplifiessubexpressions.YoudothisalltheNmewhensimplifyingmathexpressions,andwecandoitinRacket,too.E.g;
(- (* (+ 2 3) 9) (/ 18 6))
⇒ (- (* 5 9) (/ 18 6))
⇒ (- 45 (/ 18 6))
⇒ (- 45 3)
⇒ 42
38Expr/decl
Small-stepsemanNcs:intuiNon
Scanlewtorighttofindthefirstredex(nonvaluesubexpressionthatcanbereducedtoavalue)andreduceit:
(- (* (+ 2 3) 9) (/ 18 6))
⇒ (- (* 5 9) (/ 18 6))
⇒ (- 45 (/ 18 6))
⇒ (- 45 3)
⇒ 42
39Expr/decl
[addition]
[multiplication]
[division] [subtraction]
Small-stepsemanNcs:reducNonrulesThereareasmallnumberofreducNonrulesforRacket.Thesespecifytheredexesofthelanguageandhowtoreducethem.
Therulesowenrequirecertainsubpartsofaredextobe(parNcularkindsof)valuesinordertobeapplicable.
Id⇒V,whereId⟼VisthefirstbindingforIdinthecurrentenvironment*[varref]
(+ V1V2)⇒V,whereVisthesumofnumbersV1andV2[addiNon]
TherearesimilarrulesforotherarithmeNc/relaNonaloperators
(if Vtest EthenEelse) ⇒ Ethen,ifVtestisnot#f[ifnonfalse]
(if #f EthenEelse) ⇒ Eelse[iffalse]
*Inamoreformalapproach,thenotaNonwouldmaketheenvironmentexplicit.E.g.,E#env⇒V
40Expr/decl
Small-stepsemanNcs:condiNonalexample(+ (if {(< 1 2)} (* 3 4) (/ 5 6)) 7)
=> (+ {(if #t (* 3 4) (/ 5 6))} 7) [less than]
⇒ (+ {(* 3 4)} 7) [if nonfalse]
⇒ {(+ 12 7)} [multiplication]
⇒ 19 [addition]
41Expr/decl
NotesforwriNngderivaNonsintext:
o Youcanuse=>for⇒
o Usecurlybraces{…}tomarktheredex
o Usesquarebracketstonametheruleusedtoreducetheredexfromthepreviouslinetothecurrentline.
Small-stepsemanNcs:errorsasstuckexpressions
Similartobig-stepsemanNcs,wemodelerrors(dynamictypeerrors,dividebyzero,etc.)insmall-stepsemanNcsasexpressionsinwhichtheevaluaNonprocessisstuckbecausenoreducNonruleismatched.Forexample:
(- (* (+ 2 3) #t) (/ 18 6))
⇒ (- (* 5 #t) (/ 18 6))
(if (= 2 (/ (+ 3 4) (- 5 5))) 8 9)
⇒ (if (= 2 (/ 7 (- 5 5))) 8 9)
⇒ (if (= 2 (/ 7 0)) 8 9)
42Expr/decl
Small-stepsemanNcs:yourturnUsesmall-stepsemanNcstoevaluatethefollowingexpressions:
(if (< 8 2) (+ #f 5) (+ 3 4))
(if (+ 1 2) (- 3 7) (/ 9 0))
(+ (if (< 1 2) (* 3 4) (/ 5 6)) 7)
(+ (if 1 2 3) #t)
43Expr/decl
RacketDocumentaNon
RacketGuide:haps://docs.racket-lang.org/guide/RacketReference:haps://docs.racket-lang.org/reference
44Expr/decl