TExcelTAD
Home › OCaml › OCaml Functions in Depth

OCaml Functions in Depth

You already know how to define and call functions. This lesson explains what really happens with several arguments: currying and partial application, two ideas at the heart of OCaml style.

Every function takes one argument

The type of a two-argument function looks like a chain of arrows:

ocaml
# let add a b = a + b;;
val add : int -> int -> int = <fun>

The arrow associates to the right, so int -> int -> int means int -> (int -> int): add takes one int and returns a function that takes the second int. let add a b = a + b is shorthand for:

ocaml
let add = fun a -> (fun b -> a + b)

This is called currying (after the logician Haskell Curry). When you write add 2 3, OCaml applies add to 2, gets a function back, and applies that to 3.

Partial application

Because of currying, you can supply only some of the arguments. The result is a new function waiting for the rest:

ocaml · try it yourself
let add a b = a + b
let add_ten = add 10              (* int -> int *)

let greet greeting name = greeting ^ ", " ^ name ^ "!"
let hello = greet "Hello"
let welcome = greet "Welcome back"

let () =
  Printf.printf "%d %d\n" (add_ten 5) (add_ten 32);
  print_endline (hello "Ana");
  print_endline (welcome "Ben")
15 42
Hello, Ana!
Welcome back, Ben!

Partial application shines with list functions:

ocaml · try it yourself
let multiply a b = a * b

let () =
  let prices = [ 3; 8; 12 ] in
  let doubled = List.map (multiply 2) prices in
  List.iter (Printf.printf "%d ") doubled;
  print_newline ();
  let lines = [ "first"; "second" ] in
  List.iter (Printf.printf "> %s\n") lines
6 16 24 
> first
> second

multiply 2 is a function int -> int, exactly what List.map expects. Even Printf.printf "> %s\n" is a partially applied function waiting for its string.

Tip: Put the argument that changes least first. Then partial application gives you useful specialised functions, as with greet "Hello".

Tuples are not multiple arguments

You can write a function that takes a tuple, but it is a different type and cannot be partially applied:

ocaml · try it yourself
let add_curried a b = a + b         (* int -> int -> int *)
let add_tupled (a, b) = a + b       (* int * int -> int *)

let () =
  Printf.printf "%d\n" (add_curried 1 2);
  Printf.printf "%d\n" (add_tupled (1, 2))
3
3

Idiomatic OCaml uses the curried form unless the tuple is a natural unit of data, like a point (x, y).

Type annotations

You can annotate parameters and the return type when you want documentation or a clearer error message:

ocaml · try it yourself
let average (a : float) (b : float) : float = (a +. b) /. 2.0

let percent ~(part : int) ~(total : int) : float =
  100.0 *. float_of_int part /. float_of_int total

let () =
  Printf.printf "%.2f\n" (average 3.0 4.5);
  Printf.printf "%.1f%%\n" (percent ~part:3 ~total:8)
3.75
37.5%

(The ~part syntax is a labeled argument, explained in the next lesson.)

Closures

A function can use names from the scope where it was defined. It captures their values, creating a closure. Functions that build other functions rely on this:

ocaml · try it yourself
let make_discount percent =
  let factor = 1.0 -. (percent /. 100.0) in
  fun price -> price *. factor

let () =
  let summer_sale = make_discount 20.0 in
  let staff = make_discount 35.0 in
  Printf.printf "%.2f %.2f\n" (summer_sale 50.0) (staff 50.0)
40.00 32.50

Each call to make_discount produces a separate function with its own factor.

Function composition by hand

Since functions are values, combining them is easy. Here compose f g returns a function that applies g, then f:

ocaml · try it yourself
let compose f g x = f (g x)
let trim_and_upper = compose String.uppercase_ascii String.trim

let () = print_endline ("[" ^ trim_and_upper "   ocaml rocks  " ^ "]")
[OCAML ROCKS]

The standard library also provides Fun.compose, Fun.id (the identity function) and Fun.flip (swap the first two arguments).

Test yourself

Given let add a b = a + b, what is the type of add 5?

  1. int
  2. int -> int
  3. int -> int -> int
  4. A compile error

What does int -> int -> int mean exactly?

  1. (int -> int) -> int
  2. int -> (int -> int)
  3. A function taking a pair
  4. Two separate functions

Which definition can be partially applied?

  1. let f (a, b) = a + b
  2. let f a b = a + b
  3. Both
  4. Neither