6 Functions and their results
Page 1 of 9
You have written functions since chapter 1: a name, parameters, a result type and a body. This chapter looks at them closely, from the two sides of every function. From the caller's side: how a call matches its arguments to parameters, in what order it works them out, and how a dot turns a call into a method call on your own kinds. From the function's side: how its body gives back its result, what the checker does with that result, and what its header tells the rest of the program. You end with a shipping report that quotes each order of the day.
What you'll build
A shipping report. For each order of the day, the program works out the charge from the parcel's weight and the zone it ships to, ships large orders within the country for free, and gives a weekend offer to one order:
order 1042: 7.90
order 1043: ships free
order 1044: 30.90
order 1045: 15.45
order 1046: 13.90You will learn to:
- call a function with labels, in any order, with punning, and as a method on a value of your own kind;
- know the order in which a call works out its arguments, and why a call that prints stands on a line of its own;
- give back a result from a body of one line or of several, and read what the checker says when the result is wrong;
- rely on a function's header, and nothing else, when you use its result;
- choose between a public and a private function, and read the header the checker infers for a private one.
Download this chapter's packages: each step is a package under steps/, and the chapter's program is day-to-day/; run una check . and una run . in one.
Why it works this way
In a program of any size, most code is calls of functions that someone else wrote, or that you wrote months ago. A caller then has the function's header in front of it, and not its body. In many languages that header tells only part of the story. Arguments are matched by their place, so a call that swaps two numbers is accepted, and the bug shows up later in a wrong total. Whether a function prints or writes a file shows only in its body. What it promises about its result, such as "never negative", lives in a comment that nothing checks.
Una puts the whole story in the header, and checks it from both sides. A call names every argument after the first, so a swap is visible where it happens. The checker holds the body to the result type that the header states. A caller may rely on the header's promises, and only on those: the verifier never reads the body of a function to prove something about its caller. A public header also says what the function may do outside the program, and the checker refuses a body that does more.
A caller of a Una function needs only its header. The names, the types, the effects and the promises are all there, and the checker makes sure the body keeps them.
Next:6.1 Calls in depth: labels, the order of evaluation, method calls on your own kinds