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
# ;;
This page in the OCaml manual explains how
matchworks: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 thelisttype 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 thelisttype that represents non-empty lists. The::constructor takes two arguments: the head of the list and the tail of the list.headandtailare 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 variablesheadandtailto the head and the tail of the non-empty list respectively.