OCaml By Examples

match

utop

utop # let i = 1;;
val i : int = 1
OCaml offers a very powerful way to **match** patterns with the `match` keyword. Think of a `switch` or a long series of `if` and `else if` in a different language.
utop # match i with
| 0 -> print_endline "zero"
| 1 -> print_endline "one"
| _ -> print_endline "some other number";;
one
- : unit = ()
`match` are safe to use as they will not allow you to miss a pattern.
utop # let last_name first_name =
    match first_name with
    | "bill" -> "gates"
    | "elon" -> "musk"
    ;;
Lines 2-4, characters 0-18:
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
""
val last_name : string -> string = <fun>

utop # let last_name first_name =
    match first_name with
    | "bill" -> "gates"
    | "elon" -> "musk"
    | x -> "some other name: " ^ x;;
val last_name : string -> string = <fun>

utop # last_name "david";;
- : string = "some other name: david"
next: tuples