Now that we’ve seen how to construct values with algebraic data types, let’s discuss how we work with these values. If we have a value of some type, there are two things we would like to be able to do:
If the type has more than one value constructor, we need to be able to tell which value constructor was used to create the value.
If the value constructor has data components, we need to be able to extract those values.
Haskell has a simple, but tremendously useful, pattern matching facility that lets us do both of these things.
A pattern lets us look inside a value and
bind variables to the data it contains. Here’s an example of pattern
matching in action on a Bool value; we’re going to
reproduce the not
function:
-- file: ch03/add.hs myNot True = False myNot False = True
It might seem that we have two functions
named myNot
here, but Haskell lets
us define a function as a series of equations:
these two clauses are defining the behavior of the same function for
different patterns of input. On each line, the patterns are the items
following the function name, up until the =
sign.
To understand how pattern matching works,
let’s step through an example—say, myNot False
.
When we apply myNot
, the Haskell runtime checks the value
we supply against the value constructor in the first pattern. This does
not match, so it tries against the second pattern. That match succeeds,
so it uses the righthand side of that equation as the result of the
function application.
Here is a slightly ...
No credit card required