The Case for Case
I try to keep an eye out for quick wins that can improve my Haskell code. One thing that annoys me in the code I have written before is the use of pattern matching at the top level where the function name is repeated for each pattern.
greet :: Maybe String -> String
Just "Oskar") = "Ohai, me."
greet (Just "John Bonham") = "Wait... How is this happening?"
greet (Just someone) = "Hi, " ++ someone ++ "."
greet (Nothing = "People of the Earth!" greet
Greet, greet, greet, greet… Sigh. Would you agree that the repetition becomes a bit tedious? Let’s put those patterns into a case expression instead.
greet :: Maybe String -> String
= case who of
greet who Just "Oskar" -> "Ohai, me."
Just "John Bonham" -> "Wait... How is this happening?"
Just someone -> "Hi, " ++ someone ++ "."
Nothing -> "People of the Earth!"
Much better! Notice also how the parenthesis around the Maybe pattern can be removed.
If you want you can take this even further using the LambdaCase language extension. Either use the flag -XLambdaCase
when compiling or add a language pragma at the top of your module as in the following example.
{-# LANGUAGE LambdaCase #-}
module Greetings where
greet :: Maybe String -> String
= \case
greet Just "Oskar" -> "Ohai, me."
Just "John Bonham" -> "Wait... How is this happening?"
Just someone -> "Hi, " ++ someone ++ "."
Nothing -> "People of the Earth!"
If you want to find out more about syntax extensions you should check out the GHC users guide. Thanks for reading. Happy pattern matching!