typestar

Polymorphism in OCaml

'a is any type: one function, checked once, reused everywhere.

(* 'a is any type: one function, checked once, reused everywhere. *)
let middle lst =
  match lst with
  | [] -> None
  | _ -> Some (List.nth lst (List.length lst / 2))

(* A polymorphic variant of pairs works on any payload. *)
let swap (a, b) = (b, a)

let () =
  (match middle ["ebb"; "slack"; "flood"] with
   | Some phase -> print_endline ("Middle phase: " ^ phase)
   | None -> print_endline "empty tide table");
  (match middle [3; 14; 15; 92] with
   | Some n -> Printf.printf "Middle reading: %d\n" n
   | None -> print_endline "no readings");
  let hi, lo = swap (2, 9) in
  Printf.printf "Swapped: %d %d\n" hi lo

How it works

  1. middle works on string lists and int lists alike.
  2. The option return admits the empty-list case honestly.
  3. swap (a, b) is polymorphic in both slots.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
597
Tokens
144
Three-star pace
65 tpm

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

Type this snippet

Step 3 of 3 in Types, step 17 of 29 in Language basics.

← Previous Next →