In Chapter 3 of OCaml from the very beginning, I learned about pattern matching. It can replace the ‘if … then … else …’ construct, and can be easier to read. It also has the advantage that if you haven’t considered all cases in the pattern matching, OCaml will warn you so. Just for this reason, I don’t see why you would ever want to use the ‘if … then … else …’ construct instead of pattern matching.
To pattern match, use the following construct:
match (expression) with
(pattern 1) -> (value 1)
| (pattern 2) -> (value 2)
and so on. It is equivalent to saying
if (expression) = (pattern 1) then (value 1) else if (expression) = (pattern 2) then (value 2) and so on.
Make sure to separate each pattern with ‘|‘. The values the patterns matched to must be of the same type.
The else case
‘_’ represents the pattern of anything. That is,
match (expression) with
(pattern 1) -> (value 1)
| _ -> (value 2)
is equivalent to saying
if (expression) = (pattern 1) then (value 1) else (value 2)
Matching multiple patterns to one value
Multiple patterns can be matched to the same value. Just separate each pattern with ‘|’, as usual. That is,
match (expression) with
(pattern 1) | (pattern 2) | (pattern 3) -> (value 1)
| _ -> (value 2)
is equivalent to saying
if (expression) = (pattern 1) || (expression) = (pattern 2) || (expression) = (pattern 3) then (value 1) else (value 2)
Leave a Reply