Pattern matching
Pattern matching is a feature in functional programming languages such as Haskell and ML.
With certain recursive data types implemented in these programming languages, such as a list, the construction of these types form a very definite structure. For example a list is defined as an element constructed on to an empty list, or an element constructed on a list. In Haskell syntax:
a:[] -- element constructed on an empty list a:[a,a] -- element constructed on a list
The structure is thus element:list
. When pattern matching, we assert that a certain piece of data is equal to a certain pattern. FOr example, in the function:
head (element:list) = element
we assert that the first element of head
's argument is called element, and the function returns this. We know that this is the first element because of the way lists are defined, a single element constructed onto a list. This single element must be the first.
If such data does not match a pattern, an error inevitably occurs, or another subfunction with a pattern that does match this data is called to handle this data. Often this is the case for the empty list, as an empty list does not have a head (the first element that is constructed).
Pattern matching failure can often be ascribed to a type signature that is not strong enough or is incorrect.