Lesson 10 of 15
Pattern Matching
Pattern Matching
Pattern matching is one of OCaml's most powerful features. Use match ... with:
let describe n =
match n with
| 0 -> "zero"
| 1 -> "one"
| _ -> "other"
Matching Lists
let rec length lst =
match lst with
| [] -> 0
| _ :: rest -> 1 + length rest
The Wildcard _
The underscore matches anything and serves as a catch-all:
let is_zero n =
match n with
| 0 -> true
| _ -> false
Your Task
Write a function describe_list that returns "empty" for an empty list, "singleton" for a one-element list, and "long" for anything else.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.