View
18
Download
0
Category
Preview:
Citation preview
ListsofLists
CS5010ProgramDesignParadigms“Bootcamp”Lesson6.5
1©MitchellWand,2012-2015ThisworkislicensedunderaCreative Commons Attribution-NonCommercial 4.0 International License.
LearningOutcomes
• Attheendofthislesson,thestudentshouldbeableto– GiveexamplesofS-expressions– Give3reasonswhyS-expressionsareimportant–WritethedatadefinitionandtemplateforS-expressions
–WritefunctionsonS-expressionsusingthetemplate
2
S-expressions(informally)
• AnS-expressionissomethingthatiseitherastringoralistofS-expressions.
• Soifit'salist,itcouldcontainstrings,orlistsofstrings,orlistsoflistsofstrings,etc.
• Thinkofitasanestedlist,wherethere'snoboundonhowdeepthenestingcanget.
3
SomeHistory• AnS-expressionisakindofnestedlist,thatis,alistwhoseelementsmay
beotherlists.HereisaninformalhistoryofS-expressions.• S-expressionswereinventedbyJohnMcCarthy (1927-2011)forthe
programminglanguageLispin1958.McCarthyinventedLisptosolveproblemsinartificialintelligence.
• Lispintroducedlists,S-expressions,andparenthesizedsyntax.ThesyntaxofLispanditsdescendants,likeRacket,isbasedonS-expressions.
• TheuseofS-expressionsforsyntaxmakesiteasytoreadandwriteprograms:allyouhavetodoisbalanceparentheses.Thisismuchsimplerthanthesyntaxofotherprogramminglanguages,whichhavesemicolonsandotherrulesthatcanmakeprogramshardertoread.
• S-expressionsareoneofthegreatinventionsofmodernprogramming.TheyweretheoriginalideafromwhichthingslikeXMLandJSONgrew.
4
Examples"alice""bob""carole"(list "alice" "bob")(list (list "alice" "bob") "carole")(list "dave"
(list "alice" "bob") "carole")
(list (list "alice" "bob") (list (list "ted" "carole")))
5
HerearesomeexamplesofS-expressions, inlist notation
(SeeLesson4.1)
Examples
"alice""bob""carole"("alice" "bob")(("alice" "bob") "carole")("dave" ("alice" "bob") "carole")(("alice" "bob") (("ted" "carole")))
6
HerearethesameexamplesofS-expressions,inwrite notation(SeeLesson4.1).Weoftenusewritenotationbecauseitismore
compact.
DataDefinition
AnS-expressionofStrings(SoS)iseither-- aString-- aListofSoS's (LoSS)
AListofSoS's (LoSS)iseither-- empty-- (consSoS LoSS)
7
Let'swritedownaprecisedefinition:• AnS-expressioniseitherastring
oralistofS-expressions• AlistofS-expressions iseither
emptyortheconsofanS-expressionsandanother listofS-expressions.
• Notethatthedatadefinitionfor"listofS-expressions"followsthefamiliarpatternforlists.
• Thesetwodefinitionsaremutuallyrecursive,asyoucanseefromthetwoarrows
Thisismutualrecursion
SoS LoSS
8
definedintermsof
definedintermsof
DataStructures
"alice""bob""carole"("alice" "bob")
9
"alice" "bob"
AlistofS-expressionsisimplementedasasingly-linked list.Hereisanexample.
DataStructures
(("alice" "bob") "carole")
10
"carole"
"alice" "bob" Hereisaslightlymorecomplicatedexample.Observethatthefirst ofthislistisanother list.Thefirst ofthefirstisthestring"alice".
DataStructures(cont'd)
("alice" (("alice" "bob") "carole")"dave")
11
"carole"
"alice" "bob"
"alice" "dave"
Hereisastillmorecomplicatedexample.
ThetemplaterecipeQuestion Answer
Doesthedatadefinition distinguishamongdifferentsubclassesofdata?
Yourtemplateneedsasmanycondclausesassubclassesthatthedatadefinition distinguishes.
Howdothesubclassesdifferfromeachother?
Usethedifferences toformulateaconditionperclause.
Doanyoftheclausesdealwithstructuredvalues?
Ifso,addappropriateselectorexpressionstotheclause.
Doesthedatadefinition useself-references?
Formulate``naturalrecursions''forthetemplatetorepresenttheself-referencesofthedatadefinition.
Doanyofthefieldscontaincompound ormixeddata?
Ifthevalueofafieldisafoo, addacalltoafoo-fn touseit.
12
Rememberthetemplaterecipe
Template:functionscomeinpairs;; sos-fn : SoS -> ??(define (sos-fn s)(cond[(string? s) ...][else (loss-fn s)]))
;; loss-fn : LoSS -> ??(define (loss-fn los)(cond[(empty? los) ...][else (... (sos-fn (first los))
(loss-fn (rest los)))]))
13
(firstlos)isaSoS.Thisismixeddata,sothelastruleinthetemplaterecipetellsusweneedtowrapitina(sos-fn ...).
Thisismutualrecursion
sos-fn loss-fn
14
definedintermsof
definedintermsof
Onefunction,onetask
• Eachfunctiondealswithexactlyonedatadefinition.
• Sofunctionswillcomeinpairs• Writecontractsandpurposestatementstogether,or
• Writeone,andtheotheronewillappearasawishlist function
15
occurs-in?;; occurs-in? : SoS String -> Boolean;; returns true iff the given string occurs somewhere in
the given sos.;; occurs-in-loss? : LoSS String -> Boolean;; returns true iff the given string occurs somewhere in
the given loss.
16
Here'sanexampleofapairofrelatedfunctions:occurs-in? ,whichworksonaSoS,andoccurs-in-loss? ,whichworksonaLoSS.
Examples/Tests(check-equal?
(occurs-in? "alice" "alice")true)
(check-equal? (occurs-in? "bob" "alice")false)
(check-equal?(occurs-in? (list "alice" "bob")"cathy")
false)
(check-equal?(occurs-in? (list (list "alice" "bob")
"carole") "bob")
true)
(check-equal? (occurs-in? (list "alice"
(list (list "alice" "bob") "dave")
"eve")"bob")
true)17
sos-and-loss.rkt
18
sos-and-loss.rkt
19
Theinspiration forthislivecoding exercisecomesfromhere orhere. Backgroundinformation
Livecoding:sos-and-loss.rkt
• occurs-in?:http://youtu.be/w_URqq2LrQU• number-of-strings:http://youtu.be/9z-jdukgRx4
20
Theinspiration forthislivecoding exercisecomesfromhere andhere (ignorethesappymusic).Backgroundinformation
TheS-expressionpattern
Candothisforthingsotherthanstrings:An SexpOfX is either-- an X-- a ListOfSexpOfX
A ListOfSexpOfX is either-- empty-- (cons SexpOfX ListOfSexpOfX)
21
TheTemplateforSexpX;; sexp-fn : SexpOfX-> ??(define (sexp-fn s)(cond[(X? s) ...][else (losexp-fn s)]))
;; losexp-fn : ListOfSexpOfX -> ??(define (losexp-fn los)(cond[(empty? los) ...][else (... (sexp-fn (first los))
(losexp-fn (rest los)))]))
22
(firstlos)isaSexpOfX.Thisismixeddata,sothelastruleinthetemplaterecipetellsusweneedtowrapitina(sexp-fn ...).
Sexp ofSardines
An SoSardines is either-- a Sardine-- a LoSSardines
A LoSSardines is either-- empty-- (cons SoSardines
LoSSardines)
23
AnExampleoftheSexpOfX pattern.
TheTemplateforSoSardines;; sosard-fn : SoSardines -> ??(define (sosard-fn s)(cond[(sardine? s) ...][else (lossard-fn s)]))
;; lossard-fn : LoSSardines -> ??(define (lossard-fn los)(cond[(empty? los) ...][else (... (sosard-fn (first los))
(lossard-fn (rest los)))]))
24
Summary
• NestedListsoccurallthetime• Mutuallyrecursivedatadefinitions• Mutualrecursioninthedatadefinitionleadstomutualrecursioninthetemplate
• Mutualrecursioninthetemplateleadstomutualrecursioninthecode
25
MoreExamples;; number-of-strings : SoS -> Number;; number-of-strings-in-loss : LoSS -> Number;; returns the number of strings in the given sos or
loss.
;; characters-in : SoS -> Number;; characters-in-loss : LoSS -> Number;; returns the total number of characters in the strings
in the given sos or loss.
;; number-of-sardines : SoSardines -> Number;; returns the total number of sardines in the given
SoSardines.
26
Summary
• Youshouldnowbeableto:– GiveexamplesofS-expressions– Give3reasonswhyS-expressionsareimportant–WritethedatadefinitionandtemplateforS-expressions
–WritefunctionsonS-expressionsusingthetemplate
27
NextSteps
• Studythefile06-5-sos-and-loss.rktintheExamplesfolder
• Ifyouhavequestionsaboutthislesson,askthemontheDiscussionBoard
• DoGuidedPractice6.5• Goontothenextlesson
28
Recommended