isLeapYear : Int -> Bool
isLeapYear year =
let
divisibleBy number =
modBy number year == 0
in
if divisibleBy 100 then
divisibleBy 400
else
divisibleBy 4
An if
expression (if … then … else …
) is a compound expression that uses a test to determine which of two alternatives to evaluate to.
Many other languages feature a similar construct, often termed 'ternary operator'.
In this approach
This approach uses exactly two tests to determine whether a year is a leap year.
The first test is for divisibility by 100. Once we know if the year is a multiple of 100, we know which further test to perform.
- If the year is evenly divisible by 100, then
divisibleBy 100
will evaluate toTrue
and the entireif
expression will evaluate to whateverdivisibleBy 400
evaluates to. - If the year is not evenly divisible by 100, then
divisibleBy 100
isFalse
and so theif
expression evaluates todivisibleBy 4
.
This approach is not as concise as the logical-expression, but it is easier to describe, which makes it easier to comunicate the problem domain.
When to use if
?
if
expressions might be a good fit when you
- need an expression that
- chooses between exactly two options
- depending on a single
Bool
.
When you have something other than a Bool
, use case
instead.