Note that in the empty function we wrote, we immediately pattern match. For reference, here was our implementation of empty from last lesson:
let empty lst =
match lst with
| [] -> true
| h :: t -> false
This is so common, that OCaml provides an idiomatic form for it. It's a form of syntactic sugar again.
let f x y z =
match z with
| p1 -> e1
| p2 -> e2
can be rewritten as
let f x y = function
| p1 -> e1
| p2 -> e2
We can cleanup empty to use this new format:
let empty = function
| [] -> true
| h :: t -> false;;
val empty : 'a list -> bool = <fun>
empty [];;
- : bool = true
We can also implement our sum function:
let rec sum lst =
match lst with
| [] -> 0
| h :: t -> h + sum t;;
let rec sum = function
| [] -> 0
| h :: t -> h + sum t;;
val sum : int list -> int = <fun>
sum [1; 2; 3; 4]
- : int = 10
One more example with length:
let rec length lst =
match lst with
| [] -> 0
| h :: t -> 1 + length t;;
let rec length = function
| [] -> 0
| h :: t -> 1 + length t;;
val length : 'a list -> int = <fun>
length [1; 2; 3; 4; 5]
- : int = 5