Functions in OCaml

Functions are central in OCaml. We’ll learn about functions with a few different examples.

(* Here's a function that takes two ints and returns their sum as an int. *)
let plus a b =
  (* OCaml automatically returns the value of the last expression *)
  a + b

(* In OCaml, we don't need to specify types explicitly, as the type inference system
   can deduce them. However, we can add type annotations if we want to. *)
let plusPlus (a : int) (b : int) (c : int) : int =
  a + b + c

(* The main function in OCaml *)
let () =
  (* Call a function just as you'd expect, with name args *)
  let res = plus 1 2 in
  Printf.printf "1+2 = %d\n" res;

  let res = plusPlus 1 2 3 in
  Printf.printf "1+2+3 = %d\n" res

To run this OCaml program, you would typically save it in a file with a .ml extension, for example functions.ml, and then use the OCaml compiler or interpreter:

$ ocaml functions.ml
1+2 = 3
1+2+3 = 6

Alternatively, you can compile it to a native executable:

$ ocamlopt -o functions functions.ml
$ ./functions
1+2 = 3
1+2+3 = 6

There are several other features to OCaml functions. One is pattern matching, which we’ll look at in future examples.