Multiple Return Values in OCaml

OCaml supports returning multiple values from a function using tuples. This feature is commonly used in OCaml to return both a result and additional information or status from a function.

(* The int * int in this function signature shows that
   the function returns a tuple of 2 ints. *)
let vals () = (3, 7)

let main () =
  (* Here we use pattern matching to destructure the tuple
     returned by the vals function. *)
  let (a, b) = vals () in
  Printf.printf "%d\n" a;
  Printf.printf "%d\n" b;

  (* If you only want a subset of the returned values,
     use the wildcard pattern _ *)
  let (_, c) = vals () in
  Printf.printf "%d\n" c

let () = main ()

To run the program, save it as multiple_return_values.ml and use the OCaml compiler:

$ ocamlc -o multiple_return_values multiple_return_values.ml
$ ./multiple_return_values
3
7
7

In OCaml, functions always return a single value, but that value can be a tuple, which effectively allows returning multiple values. Pattern matching is used to destructure these tuples and assign values to individual variables.

OCaml’s type system ensures that you handle all returned values, making it a powerful feature for writing robust code. If you don’t need all values, you can use the wildcard pattern _ to ignore specific elements of the tuple.

Next, we’ll explore how OCaml handles functions with a variable number of arguments.