Post on 30-Dec-2021
SolvingYourProblembyGeneralization
CS5010ProgramDesignParadigmsLesson7.1
1©MitchellWand,2012-2015ThisworkislicensedunderaCreative Commons Attribution-NonCommercial 4.0 International License.
ModuleIntroduction
• Someproblemsarenoteasilysolvedbysimplyusingatemplate.
• Weshowhowtosolvemanysuchproblemsbyintroducingnewvariablescalledcontextvariables.
• Weintroduceinvariants asawayofrecordingtheassumptionsthatafunctionmakesaboutitscontext.
2
ModuleOutline
• Attheendofthismodule,youshouldbeableto– usegeneralizationwithinaproblemtosolvetheproblem
– usecontextargumentstogeneralizeoverproblemcontexts
– writeinvariantstodocumentthemeaningofacontextargument
– explainhowinvariantsdivideresponsibilitybetweenafunctionanditscallers
3
Generalization
OverConstants
OverExpressions
OverContexts
OverDataRepresentations
OverMethodImplementations
MixedData
DataRepresentations
Basics
RecursiveData
FunctionalData
Objects&Classes
Stateful Objects
DesignStrategies
Combinesimplerfunctions
Useatemplate
DivideintoCases
Callamoregeneralfunction
CommunicateviaState
Module07
4
LessonIntroduction
• InModule5,welearnedaboutgeneralizingfunctionsinordertoavoidcodeduplicationandestablishsinglepointsofcontrol.
• Inthislesson,we'llextendthosetechniquestosituationswheretheproblemitselfdemandstobegeneralizedbeforeyoucansolveit.
• Let'slookatanexample.
5
Example1:number-listnumber-list : ListOfX -> NumberedListOfXRETURNS: a list like the original, but with the
elements numbered consecutively, startingfrom 1
(number-list (list 22 44 33)) = (list (list 1 22) (list 2 44) (list 3 33))
(number-list (list 44 33)) = (list (list 1 44) (list 2 33))
6
Here'sanexampleofaproblemthat'shardtosolveusingourusualtemplateforlists.
Example1:number-listA NumberedX is a (list Int X)A NumberedListOfX is a ListOfNumberedX
Example:(list 14 "abc") is a NumberedString(list 36 "u") is a NumberedString(list
(list 14 "abc")(list 36 "u")(list 14 "abc")) is a NumberedListofString
7
Herearethedatadefinitionsforthisproblem
Let'stryusingthetemplateforListOfX
(define (number-list lst)(cond
[(empty? lst) empty][else (cons
(list 1 (first lst))(number-list (rest lst)))]))
8
Well,that'sclearlywrong!Whatcouldwork?
Weneedahelpfunction,tonumbertherestoftheliststartingfrom2
Try#2(define (number-list lst)
(cond[(empty? lst) empty][else (cons
(list 1 (first lst))(number-list-starting-from-2
(rest lst)))]))
9
Well,thislookspromising.Allwehavetodonowiswritenumber-list-starting-from-2
number-list-starting-from-2(define (number-list-starting-from-2 lst)
(cond[(empty? lst) empty][else (cons
(list 2 (first lst))(number-list-starting-from-3
(rest lst)))]))
10
Oh,dear.Nowwehavetowritenumber-list-starting-from-3
number-list-starting-from-3(define (number-list-starting-from-3 lst)
(cond[(empty? lst) empty][else (cons
(list 2 (first lst))(number-list-starting-from-4
(rest lst)))]))
11
Youshouldbeabletoguesswherethisisgoing...
Let’sgeneralize!
Addanextraparameterforthestartingpointofthenumbering.
;; number-list-from : ListOfX NonNegInt-> NumberedListOfX;; RETURNS: a list with same elements as lst, but ;; numbered starting at n.;; EXAMPLE: (number-list-from (list 88 77) 2) ;; = (list (list 2 88) (list 3 77))
12
Nowtheproblemiseasy;; STRATEGY: Use template for ListOfX;; on lst(define (number-list-from lst n)
(cond[(empty? lst) empty][else
(cons(list n (first lst))(number-list-from
(rest lst)(+ n 1)))]))
13
Andwecanrecovertheoriginal
;; STRATEGY: ;; Call a more general function
(define (number-list lst)(number-list-from lst 1))
14
Let’slookagainatnumber-elements
• Let'slookatnumber-elements again,inadifferentwaythatmaygiveussomemoreinsight.
15
Let’swatchthiswork(number-list (list 11 22 33))= (number-list-from (list 11 22 33) 1)= (cons (list 1 11)
(number-list-from (list 22 33) 2)= (cons (list 1 11)
(cons (list 2 22)(number-list-from (list 33) 3)))
= (cons (list 1 11)(cons (list 2 22)
(cons (list 3 33)(number-list-from empty 4)))
= (cons (list 1 11)(cons (list 2 22)
(cons (list 3 33)empty))) 16
Here'sanexampleofnumber-list inaction.Ineachcallofnumber-list-from,I'vemarkedtheargumentsinred.Whatdoyounoticeaboutthefirstargumentofeachcall?Whatdoyounoticeaboutthesecondargumentofeachcall?Whatistherelationshipbetweentheargumentsofeachcallandtheoriginallist,(list112233) ?
What'sgoingonhere?
• (number-list-from lst n) iscalledonthen-th sublist oftheoriginal.
• Son isthenumberofelementsintheoriginalthatareabovelst
• Thisisdeepknowledgeaboutthisfunction,whichweneedtocaptureanddocumentifwearegoingtoexplainthiscodetoanybody
17
Wedocumentthisasaninvariant;; number-list-from ;; : ListOfX NonNegInt-> NumberedListOfX;; GIVEN: a sublist slst and an integer n;; WHERE: slst is the n-th sublist;; of some list lst0;; RETURNS: <to be filled in>
18
Wedon'tknowwhatthatlistlst0 was;allweknowisthatwearelookingatitsn-th sublist.WedocumentthisknowledgebywritingitinaWHEREclause.
TheWHEREclauseiscalledan“invariant”.ItistheresponsibilityofeachcallerofthisfunctiontomakesurethattheWHEREclauseissatisfied.
ThefunctionitselfcanassumethattheWHEREclauseistrue,justasitassumesthatitsargumentssatisfyitscontract.
Nowlet’swritetherestofthepurposestatement
• Thefunctionhaslosttrackoftheoriginallist;itonlyknowsitspositionintheoriginal.
• Needtodocumenttheconnectioninthepurposestatement.
• Here'sthenewpurposestatement:
19
NewPurposeStatement;; number-list-from ;; : ListOfX NonNegInt -> NumberedListOfX;; GIVEN: a sublist slst and an integer n;; WHERE: slst is the n-th sublist of some list lst0;; RETURNS: a copy of slst numbered according to its;; position in lst0.;; strategy: Use template for ListOfX on slst
20
First,wedocumentthatwearelookingatasublist ofsomelist
Wedon'tknowwhatthatlistwas;allweknowisthatwearelookingatitsn-th sublist.WedocumentthisknowledgebywritingitinaWHEREclause.
Thisiscalledtheaccumulatorinvariant
Theextraargumentnkeepstrackofthecontext:whereweareinlst0
StructuralArgumentsandContextArguments
• Inthisexample,slst isastructuralargument:itistheargumentthatwearedoingstructuraldecompositionon.
• n isacontextargument:ittellsussomethingaboutthecontextinwhichweareworking.Itgenerallychangesateachrecursivecall,becausetherecursivecallissolvingtheprobleminaneworbiggercontext.
• TheWHERE clausetellsushowtointerpret thecontextargumentasacontext.
21
Istheinvariantsatisfiedattherecursivecall?
(define (number-list-from lst n)(cond[(empty? lst) empty][else(cons(list n (first lst))(number-list-from (rest lst) (+ n 1)))]))
22
FACT:iflst isthenthsublist oftheoriginal,then(restlst)isits(n+1)-st sublist.
So,ifthecurrentcallsatisfiestheinvariant,thentherecursivecallalsosatisfiestheinvariant.
ContextArgumentsandAccumulators
• Thebookcallscontextarguments"accumulators".
• Foreachfunctionyouwrite,youneedtobeclearonwhatthestructuralargumentis.– You'vebeendoingthatalreadyinthestrategy
• Unlikethebook,wearenotgoingtomakeabigdealoverwhatisorisnotacontextargument/accumulator.
• Wearealsonotgoingtohave"+accumulator"asastrategyorhavetemplatesfor"structuraldecomposition+accumulator".
23
Onelessthingforyoutostressover!
Thisisn'tcompletelynew:
HerearesomeexamplesofWHERE clausesthatwe'veseen(ormighthaveseen)before:
-- A Ring is a (make-ring Real Real)WHERE inner < outer
-- An TelephoneBook is a ListOfEntriesWHERE the entries are sorted by name
24
MoreexamplesofWHERE clausesunpaused-world-after-tick : World -> World
GIVEN: a WorldWHERE: the world is not pausedRETURNS: the state of the world after the next tick
ball-normal-motion-after-tick : Ball -> Ball
GIVEN: a BallWHERE: we know the ball will not hit the wall on the next
tickRETURNS: the state of the ball after the next tick.
25
Ineachcase,itistheresponsibilityofthecallertomakesuretheinvariantissatisfiedbeforethefunctioniscalled.
Andconversely,thefunctiongetstoassumethattheinvariantissatisfied.
Recipeforcontextarguments
26
RecipeforcontextargumentsIsinformationbeinglost whenyoudoastructuralrecursion?Ifso,what?
Formulateageneralizedversionoftheproblemthatworksonasubstructureofyouroriginal.Addacontextargumentthatrepresentstheinformation"above"thesubstructure.Documentthepurposeofthecontextargumentasaninvariantinyourpurposestatement.
Designandtestthegeneralizedfunction.
Define youroriginalfunctionintermsofthegeneralizedonebysupplyinganinitialvalueforthecontextargument.
Wait:whatdowemeanby"above"?
27
11
55
44
33
22
Thesenodesare"above"thesublist(4455...)
Thesublist(4455...)
Summary
• Sometimesyouneedmoreinformationthantheusualtemplategivesyou
• Sogeneralizetheproblemtoincludetheextrainformationasaparameter
• Designthegeneralizedfunction• Thendefineyouroriginalfunctionintermsofthegeneralizedone.
28