Labeled arguments in OCaml
~labels name arguments; ?optionals carry defaults.
(* ~labels name arguments; ?optionals carry defaults. *)
let log_entry ~pool ~species ?(count = 1) () =
Printf.sprintf "%s: %d %s" pool count species
let () =
print_endline (log_entry ~pool:"north" ~species:"limpet" ~count:14 ());
(* Labels free the call site from argument order. *)
print_endline (log_entry ~species:"octopus" ~pool:"ledge" ());
(* Option.value pairs with ?opt when passing along. *)
let maybe_count = Some 7 in
print_endline
(log_entry ~pool:"cove" ~species:"anemone"
?count:maybe_count ())
How it works
~pool ~speciesfree the call site from argument order.?(count = 1)defaults when the caller stays silent.?count:maybe_countpasses an option straight through.
Keywords and builtins used here
Someinlet
The run, in numbers
- Lines
- 13
- Characters to type
- 510
- Tokens
- 102
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 102 seconds.
Step 4 of 4 in Functions, step 7 of 29 in Language basics.