Question

I wish to undestand an example from book cited below. I understand that this is something about pattern matching, but where can I find full and exact description of what match expression means?

# let rec sort lst =
# match lst with
# [] -> []
# | head :: tail -> insert head (sort tail)
# and insert elt lst =
# match lst with
# [] -> [elt]
# | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail
# ;;
Was it helpful?

Solution

This page in the OCaml manual explains how match works:

The expression

match expr 
with  pattern1    ->  expr1 
| … 
| patternn    ->  exprn

matches the value of expr against the patterns pattern1 to patternn. If the matching against patterni succeeds, the associated expression expri is evaluated, and its value becomes the value of the whole match expression. The evaluation of expri takes place in an environment enriched by the bindings performed during matching. If several patterns match the value of expr, the one that occurs first in the match expression is selected. If none of the patterns match the value of expr, the exception Match_failure is raised.

That is, it tries one pattern after the other until it finds one that matches. Once it does, it returns the expression associated with that pattern (i.e. the expression on the right side of the ->). If no pattern matches, you get an exception.

Which kinds of patterns there are and what they mean is explained on this page of the manual. That's a bit much though, so here's a summary of the relevant bits:

The most important patterns are variable patterns and variant patterns:

A variable pattern is simply a variable name. This pattern always matches and allows you to refer to the matched expression by the given name on the right side of the ->. Instead of a name you can also use _, which also always matches, but doesn't allow you to refer to the value on the right side of the ->.

A variant pattern is the name of a constructor of a variant type followed by as many patterns as the constructor takes arguments. This pattern matches if the value you're matching against is using that specific constructor and if each of the elements inside that value match the corresponding patterns.

In your example, the first pattern is []. This is the constructor of the list type that represents empty lists. The [] constructors takes no arguments. So this pattern matches if the list is empty.

The second pattern is head :: tail. :: is the constructor of the list type that represents non-empty lists. The :: constructor takes two arguments: the head of the list and the tail of the list. head and tail are variable patterns that are matches against those two arguments of the :: constructor. So this pattern matches if the list is non-empty and assigns the variables head and tail to the head and the tail of the non-empty list respectively.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top