Data Definition | Template |
Representing data with primitive types:
A name is a symbol |
(no template needed for built-in primitive types) |
Structs:
(define-struct plane (brand miles mechanic))
;; A plane is a structure
;; (make-plane brand num sym)
;; where brand is the (previously-defined) structure,
;; miles is how far it's traveled since its last overhaul, and
;; mechanic is the name of the mechanic who made the last overhaul.
|
"Data extraction":
(define (template-for-plane a-plane ..)
..(plane-brand a-plane)..
..(plane-miles a-plane)..
..(plane-mechanic a-plane).. )
(If some of these parts are again themselves structures,
do not extract from those! Leave that to a separate function.)
|
Data definitions made with "or" ("unions"):
;; A kritter is one of
;; - 'kangaroo
;; - 'kiwi
;; - 'kookaburra
;; (and nothing else).
|
(define (kritter-template beastie)
(cond [(symbol=? beastie 'kangaroo) ...]
[(symbol=? beastie 'kiwi) ...]
[(symbol=? beastie 'kookaburra) ...]))
The template is a cond, with one branch per type of data,
and a question to distinguish each branch.
Note that there are no answers yet, in the template.
|
Data definitions made with "or",
where some/all branches are structures:
;; (previous definitions of plane, peach, ufo
;; as per lecture.)
;; A flying-object is one of
;; - a plane,
;; - a peach, or
;; - the symbol 'gnat
;; - a ufo
|
(define (flying-object-template afo)
(cond [(plane? afo) ..(plane-brand afo)..
..(plane-miles afo)..
..(plane-mech afo)..]
[(peach? afo) ..(peach-capacity afo)..
..(peach-seagulls afo)..]
[(symbol? afo) ..]
[(ufo? afo) ..(ufo-capacity afo)..
..(ufo-planet afo)..]))
That is, just combine the previous two examples,
for this general version.
|