Pattern Matching
Pattern matching is similar to conditional statements and allows us to chose different paths for our functions based on patterns of their arguments. These patterns can be direct values or more general patterns of arguments that the function takes in. Much like in guarded equations, the patterns are evaluated from top to bottom and the first one that matches the input arguments is selected for further evaluation. We can define our previous function cardColour using pattern matching with direct values:
1
cardColour :: String -> String
2
cardColour "hearts" = "red"
3
cardColour "diamonds" = "red"
4
cardColour "spades" = "black"
5
cardColour "clubs" = "black"
6
cardColour _ = "I am not familiar with this card suit."
7
​
8
ghci> cardColour "diamonds"
9
"red"
10
ghci> cardColour "ace"
11
"I am not familiar with this card suit."
Copied!
That is, we define multiple patterns for our function to account for different card suits and the wildcard character performs the same as we saw before in conditional statements. Pattern matching gets more powerful when we use it with lists and tuples to build larger patterns.
Copy link