OCaml Labeled and Optional Arguments
When a function has several arguments of the same type, it is easy to mix them up. Is it sub "hello" 1 3 or sub "hello" 3 1? OCaml lets you name arguments with labels, and make some of them optional with default values.
Labeled arguments
Put ~ before a parameter name to make it labeled. Callers then write ~name:value, in any order:
let rectangle_area ~width ~height = width * height
let () =
Printf.printf "%d\n" (rectangle_area ~width:4 ~height:3);
Printf.printf "%d\n" (rectangle_area ~height:3 ~width:4)12
12
The type shows the labels: width:int -> height:int -> int.
Label punning
If you already have a variable with the same name as the label, you can write just ~name:
let make_user ~name ~age = Printf.sprintf "%s (%d)" name age
let () =
let name = "Lin" in
let age = 29 in
print_endline (make_user ~name ~age)Lin (29)
The standard library uses this style in ListLabels, StringLabels and ArrayLabels, for example ListLabels.map ~f:(fun x -> x * 2) lst.
Optional arguments
A ? parameter is optional. Give it a default with ?(name = default):
let format_price ?(currency = "EUR") ?(decimals = 2) amount =
Printf.sprintf "%.*f %s" decimals amount currency
let () =
print_endline (format_price 9.5);
print_endline (format_price ~currency:"USD" 9.5);
print_endline (format_price ~decimals:0 ~currency:"JPY" 1250.0)9.50 EUR
9.50 USD
1250 JPY
(%.*f takes the number of decimals as an extra argument before the float.)
Notice that amount is the last parameter and it is not optional. This matters: OCaml decides that the optional arguments were omitted when it sees the next positional (unlabeled) argument. A function whose optional arguments come last can never "know" they were left out, and the compiler warns about it.
Tip: Rule of thumb: optional arguments first, then at least one positional argument at the end. If there is nothing natural to put last, use
().
let connect ?(host = "localhost") ?(port = 8080) () =
Printf.printf "connecting to %s:%d\n" host port
let () =
connect ();
connect ~port:443 ~host:"example.org" ()connecting to localhost:8080
connecting to example.org:443
Optional arguments without defaults
Without a default, the parameter has an option type inside the function: Some v if the caller passed it, None otherwise:
let greet ?title name =
match title with
| Some t -> "Hello, " ^ t ^ " " ^ name
| None -> "Hello, " ^ name
let () =
print_endline (greet "Rivera");
print_endline (greet ~title:"Dr." "Rivera")Hello, Rivera
Hello, Dr. Rivera
To forward an optional value you already hold as an option, use ?title:maybe_title instead of ~title:.
Labels and partial application
Labels also make partial application flexible: you can fix any labeled argument, not just the first one.
let clamp ~low ~high x = if x < low then low else if x > high then high else x
let () =
let to_percent = clamp ~low:0 ~high:100 in
let at_least_one = clamp ~low:1 ~high:max_int in
List.iter (fun x -> Printf.printf "%d " (to_percent x)) [ -5; 42; 180 ];
print_newline ();
Printf.printf "%d\n" (at_least_one 0)0 42 100
1
Quick reference
| Syntax | Meaning |
|---|---|
let f ~x = ... |
labeled argument x |
f ~x:3 |
pass 3 for label x |
f ~x |
pass the variable x for label x (punning) |
let f ?(x = 0) () = ... |
optional with default |
let f ?x () = ... |
optional; x : 'a option inside |
f ?x:opt () |
pass an option directly |
let f ~(x : int) = ... |
labeled with type annotation |
Test yourself
Given let area ~w ~h = w * h, which call is valid?
area 2 3area ~h:3 ~w:2area (w=2, h=3)area w:2 h:3
Inside let f ?limit () = ..., what is the type of limit?
int- an option, such as
int option unitlimitis not accessible
Why does let connect ?(port = 80) () = ... take a final ()?
- It is required syntax for all functions
- So the compiler knows when the optional argument was omitted
- To return unit
- To make
portmutable