23 The Function Keyword

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:

We can also implement our sum function:

let rec sum lst =
    match lst with
    | [] -> 0
    | h :: t -> h + sum t;;

One more example with length:

let rec length lst =
    match lst with
    | [] -> 0
    | h :: t -> 1 + length t;;