Lesson 6 of 16

If Expressions

If Expressions

In Haskell, if is an expression, not a statement. It always produces a value. Both branches must exist and have the same type:

absolute :: Int -> Int
absolute n = if n < 0 then -n else n

Unlike many languages, the else branch is mandatory.

In do-blocks

You can use if inside a do block too:

main :: IO ()
main = do
  let x = 10
  putStrLn (if x > 5 then "big" else "small")

Nesting

classify :: Int -> String
classify n = if n < 0 then "negative"
             else if n == 0 then "zero"
             else "positive"

Your Task

Define maxOf that returns the larger of two integers using if/then/else. Then print maxOf 17 42.

Haskell loading...
Loading...
Click "Run" to execute your code.