Writing a function: the design recipe
The order to write things in, and the order they end up in the file. It is what A1 step 5 is graded on, and it does not change for the rest of the term.
Two concrete examples, before anything else. Write the computation out twice, with real numbers in it. If you cannot write these, you are not ready to write the function — that is information, not failure.
Find what changes. Compare the two. What differs becomes the parameters; what stays the same becomes the body.
Contract — the name, the type of each parameter, and the type of the result:
fun stripe-height(height :: Number, stripes :: Number) -> Number:Purpose — one line in
doc:, saying what it computes.Examples — a
where:block, at least three, and:- Work each answer out yourself and write the answer down.
stripe-height(90, 3) is 30, notstripe-height(90, 3) is 90 / 3. Both of those catch the same broken bodies —90 / 3is worked out on its own, so it is30whatever your body says. The difference is the order you can write them in:30you can write before you have decided on a formula, and90 / 3only after. Copying the formula into your examples means they cannot tell you anything you did not already believe. - Vary every parameter. One that is
3in all three examples is a parameter you have not tested. - Make one of them awkward — a zero, a one, or something that does not divide evenly.
- Work each answer out yourself and write the answer down.
Body — last. By this point the types, the purpose and the answers are all settled, so there is very little left to get wrong.
Run it, then break it on purpose. Green means your examples and your body agree. Change one digit of the body and watch it go red, so that you know what red looks like before it happens by accident.