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 -> Intsq 0 = 1 --first patternsq n = n * n -- second patternmain = doputStrLn "The square of 5 is:" -- adding text decsriptionprint (sq 5) --calling the sq function and printing output
Explanation
In the example above:
-
In line 1, we enter the
sqfunction, 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
sqfunction and print the output.