OCaml Functions Using the function keyword


Example

The function keyword automatically has pattern matching when you define the body of your function. Observe it below:

# let foo = function
0 -> "zero"
| 1 -> "one"
| 2 -> "couple"
| 3 -> "few"
| _ -> "many";;
val foo : int -> bytes = <fun>

# foo 0;;
- : bytes = "zero"

# foo 3;;
- : bytes = "few"                                                                         

# foo 10;;
- : bytes = "many"                                                                        

# let bar = function
"a" | "i" | "e" | "o" | "u" -> "vowel"
| _ -> "consonant";;
val bar : bytes -> bytes = <fun>                                                          

# bar "a";;
- : bytes = "vowel"

# bar "k";;
- : bytes = "consonant"