typestar

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

  1. ~pool ~species free the call site from argument order.
  2. ?(count = 1) defaults when the caller stays silent.
  3. ?count:maybe_count passes an option straight through.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 4 in Functions, step 7 of 29 in Language basics.

← Previous Next →