Cuadue
Cuadue

Reputation: 3929

Convert NominalDiffTime to Real

In the documentation for Data.Time.Clock I see this:

Conversion functions will treat it as seconds. It has a precision of 10^-12 s

What function will turn that NominalDiffTime into a Double? No luck hoogling it

Upvotes: 15

Views: 2656

Answers (3)

Geradlus_RU
Geradlus_RU

Reputation: 1478

Since time-1.9.1 you can use nominalDiffTimeToSeconds from Data.Time.Clock module:

nominalDiffTimeToSeconds :: NominalDiffTime -> Pico

Get the seconds in a NominalDiffTime.

Upvotes: 1

Carl
Carl

Reputation: 27003

You need to pay more attention to the list of instances for the type. One of the listed instances is Real NominalDiffTime. This allows you to use realToFrac :: (Real a, Fractional b) :: a -> b to convert to Double, since Double is an instance of Fractional.

Since NominalDiffTime has a Real instance, and Double has a Fractional instance, you can use realToFrac as if it had the type signature NominalDiffTime -> Double. Of course, realToFrac is more polymorphic than that, and so you might need to give it hints exactly what types you want to convert sometimes. But it certainly is capable of that conversion, if it can figure out the types.

Upvotes: 18

leftaroundabout
leftaroundabout

Reputation: 120711

You can hoogle it allright, just need to make the signature a bit more general. In this case, you know both types approximate real numbers, so that's what I'd search. Admittedly, this would have required some like in this case: the equally reasonably (RealFloat a, RealFloat b) => a -> b query wouldn't have given you the correct realToFrac right at 2nd spot.

But it's always worth to try some more general ways a function you need might be defined. Normally, if some type has instances of standard classes then the module won't bother much to also export specialised versions of the same functionality.

realToFrac in particular is something of a joker that works very often for numeric conversions, perhaps 2nd-most common after fromIntegral. (Though, honestly, I don't like this function too much because mathematically, "converting a real number to a fraction" is pretty horrible, but oh well...)

Upvotes: 4

Related Questions