Branching conditionals can be written straightforwardly using the
else syntax in Haskell. Note that all three are keywords and that each branch of an
else expression must return the same type.
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 branch is not optional, and you must include the word
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
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.
You can also use guards instead of nested
if expressions. Each branch is indicated with a pipe
case declares the value of the variable.
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 they are sometimes used for readability.