DesignStrategies2:Usingatemplate
CS5010ProgramDesignParadigms“Bootcamp”Lesson2.1
©MitchellWand,2012-2014ThisworkislicensedunderaCreative Commons Attribution-NonCommercial 4.0 International License. 1
Generalization
OverConstants
OverExpressions
OverContexts
OverDataRepresentations
OverMethodImplementations
MixedData
DataRepresentations
Basics
RecursiveData
FunctionalData
Objects&Classes
Stateful Objects
DesignStrategies
Combinesimplerfunctions
Useatemplate
Callamoregeneralfunction
CommunicateviaState
Module02
2
DivideintoCases
Generalization
OverConstants
OverExpressions
OverContexts
OverDataRepresentations
OverMethodImplementations
MixedData
DataRepresentations
Basics
RecursiveData
FunctionalData
Objects&Classes
Stateful Objects
DesignStrategies
Combinesimplerfunctions
Useatemplate
Callamoregeneralfunction
CommunicateviaState
Lesson2.1
3
DivideintoCases
Introduction
• Inthislesson,wewillshowhowtotakeapartnon-scalardatausingthedestructortemplateforthattypeofdata.
• Thisisthestrategyyouwilluseforthevastmajorityofyourfunctions.
4
Let'sseewhereweare
TheFunction DesignRecipe
1.DataDesign
2.ContractandPurposeStatement
3. ExamplesandTests
4.DesignStrategy
5.FunctionDefinition
6.Program Review
5
TheSixPrinciplesofthiscourse
1.ProgrammingisaPeopleDiscipline
2.RepresentInformationasData;InterpretDataasInformation
3. Programsshouldconsistoffunctionsandmethodsthatconsumeandproducevalues
4.DesignFunctions Systematically
5.DesignSystemsIteratively
6.Passvalueswhenyoucan,sharestateonlywhenyoumust.
DesignStrategies
1.Combine simplerfunctions
2. Usetemplatefor<datadef>on<vble>
3.Divideintocaseson<condition>
4.UseHOF<mapfn>on<vble>
5.Callamoregeneralfunction
Useadestructortemplate
• Usedwhentheproblemcanbesolvedbyexaminingapieceofnon-scalardata.
• Slogan:
Theshapeofthedatadeterminestheshapeof
theprogram.6
Whatdoesitmeanto“examine”apieceofdata?
• Ifthedataiscompounddata,thismeansextractingitsfields.
• Ifthedataisitemizationdata,thismeansdeterminingwhichvariantthedatais.
• Ifthedataismixeddata,thismeansdeterminingwhichvariantthedatais,andthenextractingitsfields,ifany.
• Everydatadefinitionincludesatemplatethatshowshowthisexaminationprocessistobeorganized.
• Writingafunctionusingatemplateisaccomplishedbyfillingintheblanksofthetemplate.– Definitionof"fillingintheblank"tocomeinSlide11.
7
FromTemplatetoFunctionDefinition
RecipeforUsingaTemplate1.Make acopyofthetemplateanduncommentit2.Fill inthefunctionnameandaddmoreargumentsifneeded3.Thestrategyis“Usetemplatefor<datadef>on<vble>,”where<datadef>isthekindofdatayouaretakingapart,and<vble>isthevariablewhosevalueyouarelookingat.4.Fillintheblanksinthetemplatebycombiningtheargumentsandthevaluesofthefieldsusingsimplerfunctions.
8
Example:book-receipts;; book-receipts : Book NonNegInt -> NonNegInt;; GIVEN: a Book and the number of copies sold;; RETURNS: the total receipts from the sales of the ;; given book. Ignores the number of copies on hand.;; EXAMPLE:;; (book-receipts ;; (make-book "Felleisen" "HtdP2" 13 2795) 100);; = 279500
9
Todothis,we’llneedtolookinside theBooktoseeitsprice,sowe’llusethe
Booktemplate
1.Makeacopyofthetemplateanduncommentit
(define (book-fn b)(...
(book-author b)(book-title b)(book-on-hand b)(book-price b)))
10
2.Fillinthefunctionnameandaddmoreargumentsifneeded
(define (book-receipts b sales)(...
(book-author b)(book-title b)(book-on-hand b)(book-price b)))
11
3.Writedownthestrategy
;; STRATEGY: Use template for Book on b.(define (book-receipts b sales)(...
(book-author b)(book-title b)(book-on-hand b)(book-price b)))
12
4.Fillintheblanksinthetemplate
;; STRATEGY: Use template for Book on b.(define (book-receipts b sales)(* (book-price b) sales))
Thingswedidn’tuse:(book-author b)(book-title b)(book-on-hand b)
That’sOK!
13
Wesaid:“4.Fillintheblanksinthetemplatebycombining theargumentsandthevaluesofthefieldsusingsimpler functions.”
Example:nextstateoftrafficlight;; DATA DEFINITION:;; a TrafficLightState (TLState) is one of;; -- "red";; -- "yellow" ;; -- "green";; INTERPRETATION: self-evident
14
ContractandPurposeStatement;; next-state : TLState -> TLState;; GIVEN: a TLState;; RETURNS: the TLState that follows the given TLState;; EXAMPLES:;; (next-state "red") = "green";; (next-state "yellow") = "red";; (next-state "green") = "yellow"
15
1.Makeacopyofthetemplateanduncommentit
(define (tls-fn state)(cond[(string=? state "red") ...][(string=? state "yellow") ...][(string=? state "green") ...]))
16
2.Fillinthefunctionnameandaddmoreargumentsifneeded
(define (next-state state)(cond[(string=? state "red") ...][(string=? state "yellow") ...][(string=? state "green") ...]))
17
3.Fillinthestrategy;; STRATEGY: Use template for TLState on state
(define (next-state state)(cond[(string=? state "red") ...][(string=? state "yellow") ...][(string=? state "green") ...]))
18
4.Fillintheblanks;; STRATEGY: Use template for TLState on state
(define (next-state state)(cond[(string=? state "red") ...][(string=? state "yellow") ...][(string=? state "green") ...]))
19
Whatistheanswerfor“red”?
4.Fillintheblanks;; STRATEGY: Use template for TLState on state
(define (next-state state)(cond[(string=? state "red") "green"][(string=? state "yellow") ...][(string=? state "green") ...]))
20
Whatistheanswerfor“red”?
Answer(fromexamples):“green”
4.Fillintheblanks;; STRATEGY: Use template for TLState on state
(define (next-state state)(cond[(string=? state "red") "green"][(string=? state "yellow") "red"][(string=? state "green") ...]))
21
Whatistheanswerfor“yellow”?
Answer(fromexamples):“red”
4.Fillintheblanks;; STRATEGY: Use template for TLState on state
(define (next-state state)(cond[(string=? state "red") "green"][(string=? state "yellow") "red"][(string=? state "green") "yellow"]))
22
Whatistheanswerfor“green”?
Answer(fromexamples):“yellow”
Workingwithotherkindsofdata
• We'veseenhowtousetemplatesforcompounddataanditemizationdata
• Mixeddataworksthesameway.• Copythetemplate,uncommentit,andfillinthemissingpieces.That'sit!
• Ifyou'vethoughthardenoughaboutyourfunction,fillingintheblanksiseasy.
23
Whatcanyouputintheblanks?
• Wesaid:Fillintheblanksinthetemplatebycombiningtheargumentsandthevaluesofthefieldsusingsimplerfunctions.
• Thismeans:– Youdon'thavetouseallofthefields– Youcanuseafieldtwice– Youdon'thavetousethefields"inorder"
• Butithastobesimple,asinLesson1.7
24
NextSteps
• Study02-1-book-receipts.rktand02-2-traffic-light.rktintheExamplesfolder.– Besuretofinishtheprevious-stateexamplein02-2-traffic-light.rkt
• Ifyouhavequestionsorcommentsaboutthislesson,postthemonthediscussionboard.
• DotheGuidedPractices• Goontothenextlesson.
25