1.2 Monday Afternoon
How to represent a virtual cat, which has a number for position and a number for happiness? Just one number is possible, but awkward...
(define-struct vcat (x happiness))
Explain geneated definitions. Show some examples. Demonstrate selectors. Talk about new reduction rules and how a “value” corresponds to “the simplest form of something’s name.”
We want to write things like
; vcat-happy-enough? : vcat -> boolean
but to use vcat as a contract, we need a data definition:
; A vcat is |
; (make-vcat number number) |
(define-struct vcat (x happiness)) |
Now we can write the function. Follow the design recipe. For the body, observe that we need to pull out a field. We pretty much always need to pull out a field, and that leads to the structure design recipe.
Shape of the data → shape of the (template and) function.
Implement vcat-run, which moves the cat forward by 25.
Implement vcat-run-if-happy, which runs if the cat is happy enough.
; vcham-happy-enough? : vcham -> boolean |
; vcham-blends? : vcham string -> boolean |
; vcham-blend : vcham string -> vcham |
; a cham that already belnds becomes happier, |
; since it didn't have to work |
We’d like to design a game where some kind of animal hatches, and the game then proceeds, where an animal can be a cat or chameleon. Might need to ask
; vanimal-happy-enough? : vanimal -> boolean
but what is a vanimal? Need a new kind of data definition:
; A vanimal is either |
; * a vcat |
; * a vcham |
Start to write vanimal-happy?. At the template stage, do we have compound data? Sortof...
New design recipe and kind of template to go with a new kind of data definition. Again, template & function match the shape of the data definition.
Write
; vanimal-scare : vanimal -> vanimal
where scaring a cat makes it unhappy, while a chameleon turns orange. Three data definitions imply three templates, etc.