Haskell pattern matching – what is it?

In a nutshell, patterns are like defining piecewise functions in math. You can specify different function bodies for different arguments using patterns. When you call a function, the appropriate body is chosen by comparing the actual arguments with the various argument patterns. Read A Gentle Introduction to Haskell for more information.

Compare:

Fibonacci sequence

with the equivalent Haskell:

fib 0 = 1
fib 1 = 1
fib n | n >= 2 
      = fib (n-1) + fib (n-2)

Note the “n ≥ 2″ in the piecewise function becomes a guard in the Haskell version, but the other two conditions are simply patterns. Patterns are conditions that test values and structure, such as x:xs(x, y, z), or Just x. In a piecewise definition, conditions based on = or  relations (basically, the conditions that say something “is” something else) become patterns. Guards allow for more general conditions. We could rewrite fib to use guards:

fib n | n == 0 = 1
      | n == 1 = 1
      | n >= 2 = fib (n-1) + fib (n-2)

Leave a Comment