Meijia Lyu's Blog Always keep mind sharp

Syntax in Functions

| |

##pattern matching The sequence in pattern matching is important, patterns will be iterated from top to bottom.

sayMe :: (Integral a) => a -> String
sayMe 1 = "One"
sayMe 2 = "Two"
sayMe 3 = "Three"
sayMe n  = "Not between 1 - 3"

*Main> sayMe 3
"Three"
*Main> sayMe 5
"Not between 1 - 3"

If you reverse the sequence in the pattern matching, the result will always be “Not between 1 - 3” because the first pattern catches all inputs.

If there’s no pattern matched, the function crashes, thus we should always add a catch-all pattern in the end. This looks like Java’s switch-case syntax with a default switch, the difference is , Java won’t crash when case matches nothing.