Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 40 ยท Functions and Recursion

Labeled and Optional Arguments in OCaml

Make OCaml function calls self-documenting with labeled arguments, give parameters default values with optional arguments, and learn how labels interact with partial application.

Plain OCaml arguments are positional: copy "a.txt" "b.txt" works only if you remember which one comes first. Labeled arguments give parameters names, so call sites can read like documentation and arguments can be passed in any order. Optional arguments let a function have default behavior. Both are used heavily in the standard library (ListLabels, StringLabels, In_channel, Format) and in third-party packages.

Labeled arguments

Declare a labeled parameter with ~label:

OCAML
let area ~width ~height = width *. height

The type shows the labels:

OCAML
val area : width:float -> height:float -> float

Call it by passing ~name:value, in any order:

OCAML
# area ~width:3.0 ~height:4.0;;
- : float = 12.
# area ~height:4.0 ~width:3.0;;
- : float = 12.

When the argument is a variable with the same name as the label, there is a shorthand, punning:

OCAML
let width = 5.0 and height = 2.0
let a = area ~width ~height      (* same as ~width:width ~height:height *)

A different internal name

You can give the parameter an internal name different from the label:

OCAML
let greet ~name:person ~greeting = greeting ^ ", " ^ person

The label is name, but inside the function the value is called person.

Why labels help

OCAML
(* positional: which is source, which is target? *)
let move a b = ...

(* labeled: obvious at the call site *)
let move ~src ~dst = ...
let () = move ~src:"a.txt" ~dst:"b.txt"

Labels are especially valuable when several parameters share a type (two strings, two ints, two floats), the situation where it is easy to swap them by mistake.

Optional arguments

Add a default with ?(label = default):

OCAML
let greet ?(greeting = "Hello") name = greeting ^ ", " ^ name ^ "!"

Its type is ?greeting:string -> string -> string. The ? in the type marks the optional parameter.

OCAML
# greet "Ada";;
- : string = "Hello, Ada!"
# greet ~greeting:"Hi" "Ada";;
- : string = "Hi, Ada!"

Inside the function, the parameter is a normal value (here a string). If you leave the default out, the parameter has type 'a option: Some value when given, None otherwise.

OCAML
let describe ?prefix name =
  match prefix with
  | Some p -> p ^ " " ^ name
  | None -> name

# describe "Curie";;
- : string = "Curie"
# describe ~prefix:"Dr." "Curie";;
- : string = "Dr. Curie"

To pass a value that is already an option, use ?label:

OCAML
let maybe = Some "Prof."
let s = describe ?prefix:maybe "Turing"

The "optional argument cannot be erased" rule

An optional parameter is only omitted when the function is applied to a non-labeled argument that comes after it. This is why optional parameters should come before at least one regular parameter:

OCAML
let bad ?(n = 1) = n * 2
(* Warning: this optional argument cannot be erased *)

Here no positional parameter follows ?n, so the compiler cannot know when you are done passing arguments. A simple fix is to add a final () argument:

OCAML
let create ?(size = 16) () = Array.make size 0

let buf = create ()               (* size 16 *)
let big = create ~size:1024 ()

This () trick is the standard idiom for functions whose parameters are all optional.

Labels and partial application

Labeled arguments work with currying:

OCAML
let scale ~factor x = factor * x
let triple = scale ~factor:3      (* int -> int *)

# List.map triple [1; 2; 3];;
- : int list = [3; 6; 9]

You can supply labeled arguments in any order, even after positional ones, as long as the function's type is fully known at the call site:

OCAML
let result = scale 5 ~factor:2      (* 10 *)

A caution: when a labeled function is passed as an argument to a higher-order function, the compiler must know the label. Passing scale to List.map fails, because List.map expects 'a -> 'b and scale is factor:int -> int -> int. Use a lambda or partially apply: List.map (scale ~factor:2).

Labeled versions of the standard library

ListLabels, ArrayLabels, StringLabels, HashtblLabels, and MoreLabels are variants of the standard modules in which parameters have labels, such as ~f for the function:

OCAML
let doubled = ListLabels.map ~f:(fun x -> x * 2) [1; 2; 3]

Many Jane Street libraries (Base, Core) use ~f for the function argument everywhere, which is why you often see List.map xs ~f:(fun x -> ...).

When to use which

  • Labels for functions with several arguments of the same type, and for flags or configuration.
  • Optional arguments with defaults for sensible default behavior in libraries.
  • Positional arguments for the obvious main subject (the data), placed last so that the function works with |> and partial application.
  • Avoid optional arguments in code where functions are often passed as values; they interact awkwardly with higher-order use.

A stand-in: named parameters with defaults

JavaScript's object parameters imitate labels and defaults. The stand-in below mirrors the examples above, including Some/None via undefined.

JS Stand-in: labels and defaults via an options object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you call let area ~width ~height = ... with width 3.0 and height 4.0?

    Labeled arguments are passed as ~label:value, in any order.
  2. 2. What is punning in area ~width ~height?

    ~width is short for ~width:width when a variable of that name exists.
  3. 3. What type does an optional argument without a default have inside the function?

    Without a default, the parameter is Some v when passed and None when omitted.
  4. 4. Why does create ?(size = 16) () end with ()?

    An optional parameter is erased when a later positional argument is applied. The () provides it.

Summary

  • ~label declares labeled parameters; pass them as ~label:value in any order.
  • Punning ~x stands for ~x:x.
  • ?(label = default) declares an optional argument; without a default it is an option.
  • Optional arguments need a positional parameter after them (often ()).
  • Labels make calls self-documenting; use them for same-typed or configuration arguments.

Next: Lists