Haskell If Expressions
An if expression is a choice that produces one value. It picks between a then value and an else value, based on a condition.
A True condition picks the then value
The test 7 > 5 is True. The result is the text after then.
main :: IO ()
main = putStrLn (if 7 > 5 then "Bigger" else "Smaller")An if expression can live in a function
The function checks its score input against 50. A score of 72 takes the then branch.
passOrFail score = if score >= 50 then "Pass" else "Fail"
main :: IO ()
main = putStrLn (passOrFail 72)A False condition picks the else value
The test 3 == 4 is False. The result is the number after else.
main :: IO ()
main = print (if 3 == 4 then 100 else 200)Example
grade score = if score >= 50 then "Pass" else "Fail"
main :: IO ()
main = putStrLn (grade 85 ++ ", " ++ grade 30)Key points
- If expression: a choice between two values, written with if, then and else.
- Condition: the part after if is a Bool test that decides the result.
- Then value: the value after then is the result when the condition is True.
- Else value: the value after else is the result when the condition is False.
- Always else: an if expression must have an else part, because it must always give a value.
- A value, not an action: the result of an if expression can be stored in a binding or printed.
In this example, grade checks 85 against 50 and gives Pass. It then checks 30 and gives Fail, and the two results are joined into one line.
Note
both branches of an if expression must give the same type of value.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What does if False then "Yes" else "No" give?