In today’s Programming Praxis exercise, our goal is to implement three functions related to dates: two ways to calculate the day of the week for a given date and one to calculate the ‘doomsday’ of a given year. Let’s get started, shall we?

To make the results a bit easier to work with we make a data type with the days of the week.

data Weekday = Sun | Mon | Tue | Wed | Thu | Fri | Sat deriving (Enum, Eq, Show)

The algorithms are just a bit a math.

gauss :: Int -> Int -> Int -> Weekday
gauss y m d = toEnum $ mod (d + floor (2.6 * fromIntegral
(mod (m - 2) 12) - 0.2) + y' + div y' 4 + div c 4 - 2*c) 7 where
(c,y') = divMod (if m < 3 then y - 1 else y) 100
sakamoto :: Int -> Int -> Int -> Weekday
sakamoto y m d = toEnum $ mod (y + div y 4 - div y 100 +
div y 400 + [0,3,2,5,0,3,5,1,4,6,2,4] !! (m - 1) + d) 7
conway :: Int -> Weekday
conway y = toEnum $ mod (q + r + div r 4 + 5*(c+1) + div c 4 + 4) 7
where (c, (q,r)) = (div y 100, divMod (mod y 100) 12)

Some tests to see if everything is working properly:

main :: IO ()
main = do print $ gauss 2011 6 24 == Fri
print $ sakamoto 2011 6 24 == Fri
print $ conway 2011 == Mon

### Like this:

Like Loading...

*Related*

Tags: Haskell, programming, praxis, kata, bonsai, code, conway, date, weekday, gauss, sakamoto

This entry was posted on June 24, 2011 at 11:45 am and is filed under Programming Praxis. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

June 27, 2011 at 6:51 am |

Nice; I didn’t know about Conway’s Doomsday algorithm.