Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
Lists
CS5010ProgramDesignParadigms“Bootcamp”Lesson4.1
1©MitchellWand,2012-2014ThisworkislicensedunderaCreative Commons Attribution-NonCommercial 4.0 International License.
Howtorepresentinfoofarbitrarysize?
• aphonebookwithmanylistings• aspace-invadersgamewithmanyinvaders• apresentationwithmanyslides
• Eachofthesecanberepresentedasasequenceofinformationitems.
• Theremaybebetterwaysforsomeofthese,butwewillstartwithsequences
• Thisisourfirstexampleofrecursivedata
2
Generalization
OverConstants
OverExpressions
OverContexts
OverDataRepresentations
OverMethodImplementations
MixedData
DataRepresentations
Basics
RecursiveData
FunctionalData
Objects&Classes
Stateful Objects
DesignStrategies
Combinesimplerfunctions
Useatemplate
DivideintoCases
Callamoregeneralfunction
CommunicateviaState
Module04
Outlinefortherestofthisweek
• Thearithmeticoflists• Usingthelisttemplate• ListsofStructures
4
LearningObjectivesforthisLessonAttheendofthislesson,youshouldbeableto:• Writedownadatadefinitionforinformationrepresentedasalist
• Notatelistsusingconstructor,list,andwritenotations.
• Explainhowlistsarerepresentedassingly-linkeddatastructures,andhowcons,first,andrestworkonthesestructures
• Calculatewiththebasicoperationsonlists:cons,first,andrest .
5
Lists:AHandyConstructforSequences
• SequencesofdataitemsarisesooftenthatRackethasastandardwayofrepresentingthem.
• SequenceinformationinRacketisreprestentedbylists.
• We’llseelotsofexamples:– ListOfNumbers– ListOfDigits– ListOfStrings– ListOfBooks
6
ListsofNumbers
A List of Numbers (LON) is one of:-- empty-- (cons Number LON)
7
Listdataisakindofmixeddata.Justaswedidinourpreviousdatadefinitions, thedatadefinitions forlistsshowstheconstructor foreachcase.Herewehavetwoconstructors:theconstantemptyandthefunction cons.Alistofnumbers (or"LON")iseitherempty orthevaluebuiltbyapplyingcons toanumberandanotherLON.
There’snointerpretationherebecausetheselistsdon’tmeananything(yet).Theydonotrefertoanyreal-worldinformation.
cons isbuilt intoRacket.Wedon’t needadefine-structureforit.
ExamplesofLONsempty
(cons 11 empty)(cons 22 (cons 11 empty))
(cons 33 (cons 22 (cons 11 empty)))(cons 33 empty)
8
A List of Numbers (LON) is one of:-- empty-- (cons Number LON)
HerearesomeexamplesofLONs.
empty isaLON bythedatadefinition.
(cons11empty) isaLONbecause11 isanumberandempty isaLON.
(cons22(cons11empty)) isaLONbecause22 isanumberand(cons11empty) isaLON.Andsoon.
ListsofDigits
A Digit is one of"0" | "1" | "2" | ... | "9"
A List of Digits (LOD) is one of:-- empty-- (cons Digit LOD)
9
Let'sdoitagain,thistimewithdigits.
WedefineaDigittobeoneofthestrings"0","1",etc.,through"9".
AListofDigits(LOD)iseitheremptyortheconsofaDigitandaListofDigits.
ExamplesofLODsempty
(cons "3" empty)(cons "2" (cons "3" empty))
(cons "4" (cons "2" (cons "3" empty)))• ThesearenotLODs:(cons 4 (cons "2" (cons "3" empty)))
(cons (cons "3" empty) (cons "2" (cons "3" empty)))
10
A List of Digits (LOD) is one of:-- empty-- (cons Digit LOD)
Canyouexplainwhyeachofthefirst4examplesareLOD’s,accordingtothe
datadefinition?Canyouexplainwhythelasttwoare
notLODs?
ListsofBooks
A Book is a (make-book ...) .
A List of Books (LOB) is one of:-- empty-- (cons Book LOB)
11
Wecanbuild listsofmorecomplicateddataitems.Imaginewehadadatadefinition forBook.ThenwecandefineaListofBooksinthesamewayaswedidforlistsofnumbersorlistsofdigits:aListofBooksiseitheremptyortheconsofaBookandaListofBooks.
ExamplesofLOBs(define book1 (make-book ...))(define book2 (make-book ...))(define book3 (make-book ...))
empty(cons book1 empty)
(cons book2 (cons book1 empty))(cons book2 (cons book2 (cons book1 empty))• NotaLOB:
(cons 4 (cons book2 (cons book1 empty))
12
A List of Books (LOB) is one of:-- empty-- (cons Book LOB)
(Why?)
Thisdatadefinitionisself-referential
A List of Numbers (LON) is one of:-- empty-- (cons Number LON)
13
Thedatadefinition forLONscontainssomething wehaven'tseenbefore:self-reference.ThesecondconstructorusesLON,eventhough wehaven'tfinished definingLONsyet.That'swhatwemeanbyself-reference.Innormaldefinitions, thiswouldbeaproblem:youwouldn’t likeadictionarythatdidthis.Butself-referencethewaywe'veuseditisOK.We'veseenintheexampleshowthisworks:onceyouhavesomething thatyouknowisaLON,youcandoaconsonittobuildanotherLON.Sincethat'saLON,youcanuseittobuild stillanotherLON.Wealsocallthisarecursive datadefinition.
Thisoneisself-referential,too
A Digit is one of"0" | "1" | "2" | ... | "9"
A List of Digits (LOD) is one of:-- empty-- (cons Digit LOD)
14
HowListsRepresentSequences• IfXissomedatadefinition,wedefinealistofX'saseither
emptyortheconsofanXandalistofX's.• Soalistofsardinesiseitherempty orthecons ofasardine
andalistofsardines.• Theinterpretationisalways"asequenceofX's".
– empty representsasequencewithnoelements– (consxlst) representsasequencewhosefirstelementisx and
whoseotherelementsarerepresentedbylst.• Ifwehadsomeinformationthatwewantedtorepresentas
alistofX's(sayalistofpeople),wewouldhavetospecifytheorderinwhichtheX'sappear(say"inincreasingorderofheight"),orelsesay“inanyorder.”
15
TheGeneralPatternA ListOfX is one of-- empty
interp: a sequence of X's with no elements-- (cons X ListOfX)
interp: (cons x lst) represents a sequence of X'swhose first element is x and whoseother elements are represented by lst.
16
ListNotation• Thereareseveralwaystowritedownlists.• We'vebeenusingtheconstructornotation,sincethatisthemostimportantoneforuseindatadefinitions.
• Thesecondmostimportantnotationwewilluseislistnotation.InRacket,youcangetyouroutputinthisnotationbychoosingthelanguage"BeginningStudentwithListAbbreviations".
• Internally,listsarerepresentedassingly-linkedlists.
• Onoutput,listsmaybenotatedinwritenotation.
17
ExamplesofListNotation
18
11 22 33
Internalrepresentation:
(list 11 22 33)Listnotation:
(cons 11(cons 22
(cons 33empty))))
Constructornotation:
(11 22 33)write-style(outputonly):
Implementationofcons
19
22 33
lst
11
(cons 11 lst)
lst = (list 22 33)
(cons 11 lst) = (list 11 22 33)
Nowthatwe'veseentheinternalrepresentationoflists,wecanseehowcons createsanewlist:itsimplyaddsanewnode tothefrontofthelist.Thisoperation takesashort, fixedamountoftime.
OperationsonLists
empty? : ListOfX -> BooleanGiven a list, returns true iff the list is empty
20
Racketprovides3functions forinspectinglistsandtakingthemapart.Theseareempty?,first,andrest.
Thepredicateempty?returnstrueifandonlyifthelistisempty.
OperationsonLists
first : ListOfX -> XGIVEN: a listWHERE: the list is non-emptyRETURNS: its first element
21
Whenwewritedownthetemplateforlists,wewillseethatwhenwecallfirst, itsargumentwillalwaysbenon-empty.
OperationsonLists
rest : ListOfX -> ListOfXGIVEN: a listWHERE: the list is non-emptyRETURNS: the list of all its elements except the first
22
Whenwewritedownthetemplateforlists,wewillseethatwhenwecallrest,itsargumentwillalwaysbenon-empty.
Examples(empty? empty) = true(empty? (cons 11 empty)) = false(empty? (cons 22 (cons 11 empty))) = false
(first (cons 11 empty)) = 11(rest (cons 11 empty)) = empty
(first (cons 22 (cons 11 empty))) = 22(rest (cons 22 (cons 11 empty))) = (cons 11 empty)
(first empty) è Error! (Precondition failed)(rest empty) è Error! (Precondition failed)
23
Implementationoffirst and rest
24
22 33
lst2
11
lst2 = (list 11 22 33)(first lst2) = 11(rest lst2) = (list 22 33)
(first lst2)
(rest lst2)
first andrest simplyfollowapointerinthesingly-linkeddatastructure.
Propertiesofcons,first,andrest
(first (cons v l)) = v
(rest (cons v l)) = lIfl isnon-empty,then(cons (first l) (rest l)) = l
25
Herearesomeuseful factsaboutfirst,rest,andcons.Canyouseewhytheyaretrue? Thesefactstellusthatifwewanttobuilda
listwhosefirst isx andwhose rest islst,wecandothisbywriting (consxlst).
SummaryAtthispoint,youshouldbeableto:• Writedownadatadefinitionforinformationrepresentedasalist
• Notatelistsusingconstructor,list,andwritenotations.
• Explainhowlistsarerepresentedassingly-linkeddatastructures,andhowcons,first,andrestworkonthesestructures
• Calculatewiththebasicoperationsonlists:cons,first,andrest .
26
NextSteps
• Ifyouhavequestionsaboutthislesson,askthemontheDiscussionBoard
• DoGuidedPractices4.1and4.2• Goontothenextlesson
27