Let’s start from a simple excercise: how to fix the following error?
No instance for (Show IO (UTCTime))
when showing the current system time?
One way is
printTime = do time <- getCurrentTime print time
print =<< getCurrentTime
I want to specify a number of seconds
secondTo and wait till the system clock is showing that number of seconds.
According to a well known approach (see Mark Seemann, John A. De Goes, etc…), I try to maximize the pure logic part
syncClockTime :: UTCTime -> Rational -> Rational syncClockTime time secondTo = let (UTCTime day diff) = time secondFrom = toRational diff `mod'` 60 in if secondTo > secondFrom then secondTo - secondFrom else 60 + secondTo - secondFrom
and move the
IO to the border
waitTill :: Rational -> IO () waitTill secondTo = do print =<< getCurrentTime let waitTime = pure (syncClockTime) <*> getCurrentTime <*> pure (secondTo) print =<< waitTime delayThread waitTime print =<< getCurrentTime
waitTime line being equivalent to
time <- getCurrentTime return $ syncClockTime time secondTo