Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

haskell
pattern matching
communitycreator

What is pattern matching in Haskell?

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

haskell
pattern matching
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring