OCaml, lesson 6
Functions are the heart of OCaml. You have already used many (print_endline, int_of_string);
now you will write your own.
A function is a let binding with parameters after the name:
There is no return keyword. The body is an expression, and its value is the result. When you
call a function, arguments are separated by spaces, not commas. Put parentheses around an
argument that is itself a calculation: square (2 + 3), not square 2 + 3 (which means
(square 2) + 3).
OCaml infers a type for every function. area has the type:
Read it as "takes an int, then another int, and returns an int". The last type after the arrows is the result. You can write the types yourself to document your intent:
2 exercises to try what you just read.
A function that takes no meaningful input takes unit, and one that only prints returns unit:
Because a function takes its arguments one at a time, you can give it fewer than it wants. The result is a new function waiting for the rest:
This is handy with List.map and friends, which you will meet in the next lesson.
fun x -> x * 2 is a function without a name. It is useful when you need a small function only
once, for example List.iter (fun n -> Printf.printf "%d\n" n) numbers.
Parameters and names made with let ... in exist only inside the function body. Two functions
can each have a parameter called x without interfering. A function can also define helpers
inside itself:
Here shipping and cost are invisible outside describe_order. Keeping helpers local makes it
clear they are not meant to be used anywhere else.
A function can only use names defined above it in the file (or itself, if it is let rec).
That rule means you always know where a name comes from: look up.
A courier charges 5 for a parcel of up to 1 kg, plus 2 for every kilogram above that. Write the
function shipping weight that returns the cost for a whole number of kilograms (at least 1).
The starter reads one line of weights separated by spaces and prints the cost of each, one per
line. You only need to fill in shipping.
Sample input:
Sample output:
Write a function grade score that turns a score from 0 to 100 into a letter: 90 or more is
A, 80 or more is B, 70 or more is C, 60 or more is D, anything lower is F.
The starter reads scores, one per line, and prints each score with its letter. Fill in grade.
Sample input:
Sample output:
let square x = x * x
let area width height = width * height
let () =
Printf.printf "%d %d\n" (square 7) (area 3 4) (* 49 12 *)int -> int -> intlet average (a : float) (b : float) : float = (a +. b) /. 2.let greet () = print_endline "Welcome!" (* unit -> unit *)let add a b = a + b
let add_tax = add 5 (* int -> int *)
let () = Printf.printf "%d\n" (add_tax 20) (* 25 *)let describe_order items =
let shipping = 4 in
let cost item_price = item_price + shipping in
cost (items * 10)1 3 105
9
2395
72
4095 A
72 C
40 F