Switch in Haskell

Switch statements express conditionals across many branches.

Here’s a basic switch.

main = do
    let i = 2
    putStrLn $ "Write " ++ show i ++ " as "
    case i of
        1 -> putStrLn "one"
        2 -> putStrLn "two"
        3 -> putStrLn "three"

You can use commas to separate multiple expressions in the same case statement. We use the optional default case in this example as well.

import Data.Time

main = do
    now <- getCurrentTime
    let day = utctDayTime now
    case (toEnum . fromEnum $ (utctDayTime now) `mod` 7) of
        6 -> putStrLn "It's the weekend"
        7 -> putStrLn "It's the weekend"
        _ -> putStrLn "It's a weekday"

switch without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants.

import Data.Time

main = do
    now <- getCurrentTime
    let t = utctDayTime now
    case () of
        _ | hour t < 12 -> putStrLn "It's before noon"
        _ -> putStrLn "It's after noon"

hour :: DiffTime -> Int
hour time = floor (time / 3600) `mod` 24

A type switch compares types instead of values. You can use this to discover the type of an interface value. In this example, the variable t will have the type corresponding to its clause.

import Data.Typeable

whatAmI :: Typeable a => a -> IO ()
whatAmI i = case typeOf i of
    t | t == typeOf True -> putStrLn "I'm a bool"
    t | t == typeOf (1 :: Int) -> putStrLn "I'm an int"
    _ -> putStrLn $ "Don't know type " ++ show (typeOf i)

main = do
    whatAmI True
    whatAmI (1 :: Int)
    whatAmI "hey"
$ runhaskell switch.hs
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type [Char]

Next example: Arrays.