Switch in OCaml

Here’s the markdown content translating the provided code to OCaml:

Switch statements express conditionals across many branches.

let () =
  (* Here's a basic switch. *)
  let i = 2 in
  Printf.printf "Write %d as " i;
  match i with
  | 1 -> print_endline "one"
  | 2 -> print_endline "two"
  | 3 -> print_endline "three"
  | _ -> ()

You can use commas to separate multiple expressions in the same case statement. We use the optional default case in this example as well.

let () =
  let weekday = Unix.localtime (Unix.time ()) in
  match weekday.tm_wday with
  | 0 | 6 -> print_endline "It's the weekend"
  | _ -> print_endline "It's a weekday"

match without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants.

let () =
  let t = Unix.localtime (Unix.time ()) in
  match () with
  | _ when t.tm_hour < 12 -> print_endline "It's before noon"
  | _ -> print_endline "It's after noon"

A type switch compares types instead of values. You can use this to discover the type of an interface value. In this example, the function whatAmI will analyze the type of its argument.

let what_am_i i =
  match i with
  | `Bool _ -> print_endline "I'm a bool"
  | `Int _ -> print_endline "I'm an int"
  | _ -> Printf.printf "Don't know type %s\n" (Obj.extension_name i)
;;

what_am_i (`Bool true);
what_am_i (`Int 1);
what_am_i (`String "hey")
$ ocamlc -o switch switch.ml
$ ./switch
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string

Next example: Arrays.