What is pattern matching in Haskell?

Overview

We use pattern matching in Haskell to simplify our codes by identifying specific types of expression. We can also use if-else as an alternative to pattern matching.

Pattern matching can also be seen as a kind of dynamic polymorphism where, based on the parameter list, different methods can be executed.

Check the following example to see how to carry out a simple pattern match.

Example

sq :: Int -> Int
sq 0 = 1 --first pattern
sq n = n * n -- second pattern
main = do
putStrLn "The square of 5 is:" -- adding text decsription
print (sq 5) --calling the sq function and printing output

Explanation

In the example above:

  • In line 1, we enter the sq function, which squares a number.

  • In line 2, we create our first pattern to match for zero.

  • In line 3, we create our second pattern to square any other supplied value besides 0.

  • In line 6, we add a text description for our output.

  • In line 7, we call the sq function and print the output.

Free Resources