Skip to content

Latest commit

 

History

History
76 lines (61 loc) · 2.27 KB

index.org

File metadata and controls

76 lines (61 loc) · 2.27 KB

Exercism.io → Haskell → Leap

Leap

Write a program that will take a year and report if it is a leap year.

The tricky thing here is that a leap year occurs:

on every year that is evenly divisible by 4
  except every year that is evenly divisible by 100
    unless the year is also evenly divisible by 400

For example, 1997 is not a leap year, but 1996 is. 1900 is not a leap year, but 2000 is.

If your language provides a method in the standard library that does this look-up, pretend it doesn’t exist and implement it yourself.

Notes

For a delightful, four minute explanation of the whole leap year phenomenon, go watch this youtube video

Source

JavaRanch Cattle Drive, exercise 3 view source

Solution

module LeapYear (isLeapYear) where

isLeapYear takes an Integral and returns a Bool, satisfying the equation:

\[ \text{isLeapYear}(year) = \begin{cases} True & \text{if } 400\ |\ year
False & \text{if } 100\ |\ year \ True & \text{if } 4\ |\ year \ False & \text{otherwise} \end{cases} \]

isLeapYear :: Integral a => a -> Bool
isLeapYear year
  | 400 `divides` year = True
  | 100 `divides` year = False
  | 4   `divides` year = True
  | otherwise          = False

divides is an infix function that takes two Integral numbers and satisfies the equation:

$$d\ \text{divides}\ n = (n\ \text{rem}\ d ≡ 0)$$

divides :: Integral a => a -> a -> Bool
d `divides` n = n `rem` d == 0

Tests

runhaskell leap_test.hs
Cases: 4  Tried: 4  Errors: 0  Failures: 0