In this section Haskell's pattern-matching process will be explained in greater detail. Haskell defines a fixed set of patterns for use in case expressions and function definitions. Pattern matching is permitted using the constructors of any type, whether user-defined or predefined in Haskell. This includes tuples, strings, numbers, characters, and so on. For example, here's a contrived function that matches against a tuple of “constants:”
contrived :: ([a], Char, (Int, Float), String, Bool) → Bool
contrived ([], ′b′ (1, 2.0), “hi”, True)
= False
This example also demonstrates that nesting of patterns is permitted (to arbitrary depth).
Technically speaking, formal parameters to functions are also patterns – it's just that they never fail to match a value. As a “side effect” of a successful match, the formal parameter is bound to the value it is being matched against. For this reason, patterns in any one equation are not allowed to have more than dne occurrence of the same formal parameter.
A pattern that may fail to match is said to be refutable; for example, the empty list [ ] is refutable. Patterns such as formal parameters that never fail to match are said to be irrefutable. There are two other kinds of irrefutable patterns, which are summarized below.
The first pattern is known as a wildcard. Another common situation is matching against a value we really care nothing about. For example, the functions head and tail can be written as:
head (x :-) = x
tail (-: xs) = xs
in which we have “advertised” the fact that we don't care what a certain part of the input is. Each wildcard will independently match anything, but in contrast to a formal parameter, each will bind nothing; for this reason more than one are allowed in an equation.
The second kind of irrefutable pattern in Haskell is called a lazy pattern, and has the form ̃pat.