TL;DR: A library to specify time units easily
It has come to my attention that sometimes as a library developer, there is no easy way to specify time in asynchronous functions. One particular example comes to mind:
threadDelay :: Int -> IO ()
One thing I find disturbing about this signature, is that just by its types I can’t tell what this function is expecting, is it milliseconds, seconds, minutes? Most of Haskell standard library functions that work with time in one way or another use microseconds as the standard unit; sadly the standard library for some reason doesn’t provide an alias for
Int so that the signature could be the documentation.
Another problem that I normally have is: what happens if I’m developing a library that works with time, that uses an internal API that works in millisecond units? should I use the same
Int and expect milliseconds, or should I expect microseconds and do the transformations myself inside the function. Is this the right way to go?
After playing with
distributed-process-platform (a.k.a Cloud Haskell’s OTP), one thing that got my attention was the fact that they used a type for different time units, replicating their effort into a way less ambitious library I came up with this:
main :: IO ()
main = do
threadDelay (microSeconds 3000)
threadDelay (milliSeconds 500)
threadDelay (seconds 3)
threadDelay (minutes 1)
threadDelay (hours 1)
Providing time intervals this way looks more appealing to me, I can specify the units myself on the function (not common knowledge required). If you are a library developer and need to have one specific time unit, you can get the right unit easily using a transformation function.
-- threadDelay is already implemented by Tiempo, but I'm
-- providing the definition here for the sake of completeness
import qualified Control.Concurrent as Concurrent
threadDelay :: TimeInterval -> IO ()
threadDelay interval = Concurrent.threadDelay (toMicroSeconds interval)
Independently of the unit specified by the client code, I can get the unit I require to satisfy the spec of a lower API.
Hopefully you will find this library as useful as I do, and kudos for the devs from Cloud Haskell to provide this little yet awesome idea.