12

Using the time library (time-1.5), I have a constant, e.g. 1 second. I don't see a way to create a NominalDiffTime, so I have created a DiffTime:

twoSeconds = secondsToDiffTime 2

Now I'd like to interact with a UTCTime:

now <- getCurrentTime
let twoSecondsAgo = addUTCTime (-twoSeconds) now

Which of course doesn't type check because addUTCTime expects a NominalDiffTime in argument 1 and I have passed a DiffTime. How do I convert between the two types? Or how can I create a NominalDiffTime of 2 seconds?

Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
Daniel K
  • 887
  • 6
  • 13

2 Answers2

18

NominalDiffTime and DiffTime both have RealFrac instances and thus both Fractional and Real instances.

You can convert either of them to the other by

fromRational . toRational

Which has type (Real a, Fractional c) => a -> c. This is a very common thing to do, and is provided in the standard prelude.

realToFrac     :: (Real a, Fractional b) => a -> b
realToFrac      =  fromRational . toRational

DiffTime and NominalDiffTime both have Num and Fractional instances. This means you can use both integer and floating literals in place of either of them. All of the following work without any additional ceremony.

addUTCTime (-2)
addUTCTime 600
addUTCTime 0.5
Cirdec
  • 24,019
  • 2
  • 50
  • 100
  • 3
    `toRational` can potentially be a very expensive operation because it needs to compute `gcd` for numerator and denominator. This will also work: `fromIntegral . diffTimeToPicoseconds :: DiffTime -> NominalDiffTime`. – Mikkel Feb 27 '17 at 11:29
13

Since NominalDiffTime is an instance of Num, you can create it with fromInteger.

>>> fromInteger 1 :: NominalDiffTime
1s
snak
  • 6,483
  • 3
  • 23
  • 33
  • 5
    Due to how numeric literals work, you can just write `1 :: NominalDiffTime`. `1` already has type `Num a => a`. http://www.haskell.org/onlinereport/basic.html#numeric-literals – Cirdec Sep 12 '14 at 13:52
  • Yes, you're right. I was just thinking about converting from non-literal integer. Thank you for pointing this out. – snak Sep 12 '14 at 14:38