Haskell Language Pattern Matching


Haskell supports pattern matching expressions in both function definition and through case statements.

A case statement is much like a switch in other languages, except it supports all of Haskell's types.

Let's start simple:

longName :: String -> String
longName name = case name of
                   "Alex"  -> "Alexander"
                   "Jenny" -> "Jennifer"
                   _       -> "Unknown"  -- the "default" case, if you like

Or, we could define our function like an equation which would be pattern matching, just without using a case statement:

longName "Alex"  = "Alexander"
longName "Jenny" = "Jennifer"
longName _       = "Unknown"

A more common example is with the Maybe type:

data Person = Person { name :: String, petName :: (Maybe String) }

hasPet :: Person -> Bool
hasPet (Person _ Nothing) = False
hasPet _ = True  -- Maybe can only take `Just a` or `Nothing`, so this wildcard suffices

Pattern matching can also be used on lists:

isEmptyList :: [a] -> Bool
isEmptyList [] = True
isEmptyList _  = False

addFirstTwoItems :: [Int] -> [Int]
addFirstTwoItems []        = []
addFirstTwoItems (x:[])    = [x]
addFirstTwoItems (x:y:ys)  = (x + y) : ys

Actually, Pattern Matching can be used on any constructor for any type class. E.g. the constructor for lists is : and for tuples ,