Skip to content

Instantly share code, notes, and snippets.

@Sintrastes
Last active August 29, 2015 14:28
Show Gist options
  • Save Sintrastes/a907808e85728b05e5c9 to your computer and use it in GitHub Desktop.
Save Sintrastes/a907808e85728b05e5c9 to your computer and use it in GitHub Desktop.
-- Simple time module, no fuss over real world complications, just a simple way
-- to calculate sums and differenes of hours and minutes on a 12 hour
-- clock using divs and mods.
module SimpleTime where
-- Time in a simple hour:minute format
data Time = Time Int Int
-- Helper function to display times correctly
show2Digits m | (length $ show m) == 1 = "0" ++ show m
| otherwise = show m
showHour h | h == 0 = "12"
| otherwise = show h
instance Show Time where
show (Time h m) = (showHour h) ++ ":" ++ (show2Digits m)
-- Safe constructor for time
infixr 9 %:
(%:) :: Int -> Int -> Maybe Time
h%:m | (h <= 12) && (h >= 0) &&
(m <= 60) && (m >= 0) = Just (Time h m)
| otherwise = Nothing
-- Unsafe constructor for time -- throws error on improper format.
infixr 9 !:
(!:) :: Int -> Int -> Time
h!:m | (h <= 12) && (h >= 0) &&
(m <= 60) && (m >= 0) = Time h m
| otherwise = error "Bad time format."
infixr 8 %+
(Time h1 m1) %+ (Time h2 m2) = Time ((h1+h2+((m1+m2)`div`60)) `mod` 12) ((m1 + m2) `mod` 60)
infixr 8 %-
(Time h1 m1) %- (Time h2 m2) = Time ((h1-h2+((m1-m2)`div`60)) `mod` 12) ((m1 - m2) `mod` 60)
-- Examples
main = do
print $ 7!:30 %+ 0!:30
print $ 7!:30 %- 7!:31
print $ 7!:30 %- 7!:30
print $ 7!:30 %+ 8!:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment