Created
March 1, 2014 01:33
-
-
Save nh2/9283479 to your computer and use it in GitHub Desktop.
Natural time in Haskell: `2 hours + 4 seconds`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {-# LANGUAGE FlexibleInstances, GeneralizedNewtypeDeriving #-} | |
| newtype TimeUnit = TimeUnit Integer -- how many microseconds | |
| deriving (Eq, Show, Num) | |
| instance Num (TimeUnit -> TimeUnit) where | |
| fromInteger n = \(TimeUnit scale) -> TimeUnit (n * scale) | |
| -- a + b = ... -- task for you | |
| seconds, minutes, hours, days :: TimeUnit | |
| seconds = TimeUnit 1000000 | |
| minutes = 60 seconds -- wow | |
| hours = 60 minutes -- such natural | |
| days = 24 hours | |
| say :: String -> TimeUnit -> IO () | |
| say msg time = putStrLn $ "This is " ++ msg ++ show time | |
| -- Examples | |
| main = do | |
| say "3 minutes: " (3 minutes) | |
| say "100 days: " (100 days ) | |
| say "2 hours + 4 seconds: " (2 hours + 4 seconds) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Of course this also works if you would like your
3 minutesto be a plainIntegerinstead of a more type-safeTimeUnit:{-# LANGUAGE FlexibleInstances #-} instance Num (Integer -> Integer) where fromInteger n = \scale -> n * scale seconds, minutes, hours, days :: Integer seconds = 1000000 -- microseconds minutes = 60 seconds -- wow hours = 60 minutes -- such natural days = 24 hours say :: String -> Integer -> IO () say msg time = putStrLn $ "This is " ++ msg ++ show time main = say "3 minutes: " (3 minutes)