If Else in Haskell

Branching with if and else in Haskell is straightforward, although it differs from imperative languages in some aspects.

main :: IO ()
main = do
    -- Here's a basic example.
    if 7 `mod` 2 == 0
        then putStrLn "7 is even"
        else putStrLn "7 is odd"

    -- You can have an `if` statement without an else.
    -- In Haskell, this is typically done using guards.
    let checkDivisibility x = 
            | x `mod` 4 == 0 = putStrLn "8 is divisible by 4"
            | otherwise = return ()
    checkDivisibility 8

    -- Logical operators like `&&` and `||` are often useful in conditions.
    if 8 `mod` 2 == 0 || 7 `mod` 2 == 0
        then putStrLn "either 8 or 7 are even"
        else return ()

    -- In Haskell, we use `let` or `where` for local bindings.
    -- Here's an example using `let`:
    let num = 9
    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"

Note that in Haskell, if-then-else is an expression that always returns a value. The else part is mandatory. For more complex branching, pattern matching or guards are often used.

To run the program:

$ runhaskell if-else.hs
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

In Haskell, there’s no direct equivalent to the ternary operator, but the if-then-else expression can be used inline for similar purposes.