+ All Categories
Home > Documents > “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many...

“Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many...

Date post: 20-Jul-2020
Category:
Upload: others
View: 0 times
Download: 0 times
Share this document with a friend
27
Lists CS 5010 Program Design Paradigms “Bootcamp” Lesson 4.1 1 © Mitchell Wand, 2012-2014 This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.
Transcript
Page 1: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

Lists

CS5010ProgramDesignParadigms“Bootcamp”Lesson4.1

1©MitchellWand,2012-2014ThisworkislicensedunderaCreative Commons Attribution-NonCommercial 4.0 International License.

Page 2: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

Howtorepresentinfoofarbitrarysize?

• aphonebookwithmanylistings• aspace-invadersgamewithmanyinvaders• apresentationwithmanyslides

• Eachofthesecanberepresentedasasequenceofinformationitems.

• Theremaybebetterwaysforsomeofthese,butwewillstartwithsequences

• Thisisourfirstexampleofrecursivedata

2

Page 3: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

Generalization

OverConstants

OverExpressions

OverContexts

OverDataRepresentations

OverMethodImplementations

MixedData

DataRepresentations

Basics

RecursiveData

FunctionalData

Objects&Classes

Stateful Objects

DesignStrategies

Combinesimplerfunctions

Useatemplate

DivideintoCases

Callamoregeneralfunction

CommunicateviaState

Module04

Page 4: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

Outlinefortherestofthisweek

• Thearithmeticoflists• Usingthelisttemplate• ListsofStructures

4

Page 5: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

LearningObjectivesforthisLessonAttheendofthislesson,youshouldbeableto:• Writedownadatadefinitionforinformationrepresentedasalist

• Notatelistsusingconstructor,list,andwritenotations.

• Explainhowlistsarerepresentedassingly-linkeddatastructures,andhowcons,first,andrestworkonthesestructures

• Calculatewiththebasicoperationsonlists:cons,first,andrest .

5

Page 6: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

Lists:AHandyConstructforSequences

• SequencesofdataitemsarisesooftenthatRackethasastandardwayofrepresentingthem.

• SequenceinformationinRacketisreprestentedbylists.

• We’llseelotsofexamples:– ListOfNumbers– ListOfDigits– ListOfStrings– ListOfBooks

6

Page 7: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

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.

Page 8: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

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.

Page 9: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

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.

Page 10: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

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?

Page 11: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

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.

Page 12: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

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?)

Page 13: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

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.

Page 14: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

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

Page 15: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

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

Page 16: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

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

Page 17: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

ListNotation• Thereareseveralwaystowritedownlists.• We'vebeenusingtheconstructornotation,sincethatisthemostimportantoneforuseindatadefinitions.

• Thesecondmostimportantnotationwewilluseislistnotation.InRacket,youcangetyouroutputinthisnotationbychoosingthelanguage"BeginningStudentwithListAbbreviations".

• Internally,listsarerepresentedassingly-linkedlists.

• Onoutput,listsmaybenotatedinwritenotation.

17

Page 18: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

ExamplesofListNotation

18

11 22 33

Internalrepresentation:

(list 11 22 33)Listnotation:

(cons 11(cons 22

(cons 33empty))))

Constructornotation:

(11 22 33)write-style(outputonly):

Page 19: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

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.

Page 20: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

OperationsonLists

empty? : ListOfX -> BooleanGiven a list, returns true iff the list is empty

20

Racketprovides3functions forinspectinglistsandtakingthemapart.Theseareempty?,first,andrest.

Thepredicateempty?returnstrueifandonlyifthelistisempty.

Page 21: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

OperationsonLists

first : ListOfX -> XGIVEN: a listWHERE: the list is non-emptyRETURNS: its first element

21

Whenwewritedownthetemplateforlists,wewillseethatwhenwecallfirst, itsargumentwillalwaysbenon-empty.

Page 22: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

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.

Page 23: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

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

Page 24: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

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.

Page 25: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

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).

Page 26: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

SummaryAtthispoint,youshouldbeableto:• Writedownadatadefinitionforinformationrepresentedasalist

• Notatelistsusingconstructor,list,andwritenotations.

• Explainhowlistsarerepresentedassingly-linkeddatastructures,andhowcons,first,andrestworkonthesestructures

• Calculatewiththebasicoperationsonlists:cons,first,andrest .

26

Page 27: “Bootcamp” Lesson 4 · “Bootcamp” Lesson 4.1 1 ... • a space-invaders game with many invaders • a presentation with many slides • Each of these can be represented as

NextSteps

• Ifyouhavequestionsaboutthislesson,askthemontheDiscussionBoard

• DoGuidedPractices4.1and4.2• Goontothenextlesson

27


Recommended