Skip to content

Instantly share code, notes, and snippets.

@nh2
Created March 1, 2014 01:33
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nh2/9283479 to your computer and use it in GitHub Desktop.
Save nh2/9283479 to your computer and use it in GitHub Desktop.
Natural time in Haskell: `2 hours + 4 seconds`
{-# 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)
@nh2
Copy link
Author

nh2 commented Mar 1, 2014

Of course this also works if you would like your 3 minutes to be a plain Integer instead of a more type-safe TimeUnit:

{-# 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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment