typestar

Functors in OCaml

Module-level functions: Map.Make builds a map from an ordering.

(* A functor is a module-level function: give it a module, get one
   back. Map.Make builds a map keyed by any ordered type. *)
module PoolMap = Map.Make (String)

let counts =
  PoolMap.empty
  |> PoolMap.add "north" 12
  |> PoolMap.add "ledge" 31
  |> PoolMap.add "cove" 5

let () =
  Printf.printf "Ledge count: %d\n" (PoolMap.find "ledge" counts);
  Printf.printf "Pools mapped: %d\n" (PoolMap.cardinal counts);
  (* Adds return new maps; the old binding is untouched. *)
  let more = PoolMap.add "shelf" 9 counts in
  Printf.printf "Before %d, after %d\n"
    (PoolMap.cardinal counts) (PoolMap.cardinal more);
  PoolMap.iter (Printf.printf "%s=%d ") counts;
  print_newline ()

How it works

  1. Map.Make (String) manufactures a whole map module.
  2. Adds pipeline: each returns a new, bigger map.
  3. cardinal counts; the original map never changes.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
653
Tokens
130
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 130 seconds.

Type this snippet

Step 2 of 2 in Modules, step 23 of 29 in Language basics.

← Previous Next →