Case Expressions
Syntax
case expression of
pattern -> result
pattern -> result
pattern -> result
case expression and pattern matching
pattern matching in function definitions is syntactic sugar
for case expressions.
Rewite the previous pattern matching example code:
lucky' :: Int -> String
lucky' xs = case xs of
7 -> "LUCKY NUMBER SEVEN!"
x -> "Sorry, you're out of luck, pal!"
-
case expressions are expressions, can be used pretty much anywhere.
-
pattern matching on function parameters can only be done when defining functions.
describeList :: forall a.Array String -> String
describeList xs = "The array is " <> case xs of
[] -> "empty."
[x] -> "a singleton array."
xs -> "a longer array."load and run in repl:
> describeList []
"The list is empty."
> describeList ["a"]
"The list is a singleton list."
> describeList ["a", "b", "c"]
"The list is a longer list."