If-then-else

Branching conditionals can be written straightforwardly using the if-then-else syntax in Haskell. Note that all three are keywords and that each branch of an if-then-else expression must return the same type.

import Control.Monad (when)

The condition in the if clause must evaluate to a Boolean. Here, even evaluates to True when its argument is an even number. A conditional expression that starts with if must have both a then and an else; the else branch is not optional, and you must include the word then.

main =
  do
    if (even 7)
      then putStrLn "7 is even"
      else putStrLn "7 is odd"

You can write the equivalent of an else-less conditional using when instead of if. Note that when isn’t available by default but is imported from Control.Monad.

    when (8 `mod` 4 == 0) $
      putStrLn "8 is divisible by 4"

You can use let to preface conditionals with statements. Variables declared in the let statement are available in all branches, but not outside of this expression.

    let num = 9 in
      if num < 0
        then putStrLn (show num ++ " is negative")
        else
          if num < 10
            then putStrLn (show num ++ " has 1 digit")
            else putStrLn (show num ++ " has multiple digits")

You can also use pattern guards instead of nested if expressions. Each branch is indicated with a pipe |. Here, case declares the value of the variable.

    case 19 of
      num
        | num < 0   -> putStrLn (show num ++ " is negative")
        | num < 10  -> putStrLn (show num ++ " has 1 digit")

In case the other branches were False and thus did not return their values, an otherwise branch ensure all cases are covered and prevents a runtime error.

Parentheses are not required around expressions in the if clause or either of the branches, but we sometimes include them for clarity.

        | otherwise -> putStrLn (show num ++ " has multiple digits")

Running the program gives us no unpleasant surprises.

$ runhaskell if-else.hs
7 is odd
8 is divisible by 4
9 has 1 digit
19 has multiple digits

Next: