Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get system time in Haskell using Data.Time.Clock?

I'm needing some Ints to use as seed to random number generation and so I wanted to use the old trick of using the system time as seed.

So I tried to use the Data.Time package and I managed to do the following:

import Data.Time.Clock

time = getCurrentTime >>= return . utctDayTime

When I run time I get things like:

Prelude Data.Time.Clock> time
55712.00536s

The type of time is IO DiffTime. I expected to see an IO Something type as this depends on things external to the program. So I have two questions:

a) Is it possible to somehow unwrap the IO and get the underlying DiffTime value?

b) How do I convert a DiffTime to an integer with it's value in seconds? There's a function secondsToDiffTime but I couldn't find its inverse.

like image 334
Rafael S. Calsaverini Avatar asked Jan 21 '10 15:01

Rafael S. Calsaverini


3 Answers

a) Of course it is possible to get the DiffTime value; otherwise, this function would be rather pointless. You'll need to read up on monads. This chapter and the next of Real World Haskell has a good introduction.

b) The docs for DiffTime say that it's an instance of the Real class, i.e. it can be treated as a real number, in this case the number of seconds. Converting it to seconds is thus a simple matter of chaining conversion functions:

diffTimeToSeconds :: DiffTime -> Integer
diffTimeToSeconds = floor . toRational
like image 182
Thomas Avatar answered Nov 15 '22 23:11

Thomas


Is it possible to somehow unwrap the IO and get the underlying DiffTime value?

Yes. There are dozens of tutorials on monads which explain how. They are all based on the idea that you write a function that takes DiffTime and does something (say returning IO ()) or just returns an Answer. So if you have f :: DiffTime -> Answer, you write

time >>= \t -> return (f t)

which some people would prefer to write

time >>= (return . f) 

and if you have continue :: DiffTime -> IO () you have

time >>= continue

Or you might prefer do notation:

do { t <- time
   ; continue t  -- or possibly return (f t)
   }

For more, consult one of the many fine tutorals on monads.

like image 21
Norman Ramsey Avatar answered Nov 15 '22 21:11

Norman Ramsey


If you are planning to use the standard System.Random module for random number generation, then there is already a generator with a time-dependent seed initialized for you: you can get it by calling getStdGen :: IO StdGen. (Of course, you still need the answer to part (a) of your question to use the result.)

like image 37
Reid Barton Avatar answered Nov 15 '22 22:11

Reid Barton