我需要一些 Int
s 用作随机数生成的种子,所以我想使用使用系统时间作为种子的旧技巧。
所以我尝试使用 Data.Time 包,我设法做到了以下几点:
import Data.Time.Clock
time = getCurrentTime >>= return . utctDayTime
当我运行时间时,我会得到如下信息:
Prelude Data.Time.Clock> time
55712.00536s
time
的类型是 IO DiffTime
.我预计会看到 IO Something
类型,因为这取决于程序外部的东西。所以我有两个问题:a) 是否有可能以某种方式打开 IO 并获得底层 DiffTime 值?
b) 如何将 DiffTime 转换为整数,其值以秒为单位?有函数
secondsToDiffTime
但我找不到它的倒数。
最佳答案
Is it possible to somehow unwrap the IO and get the underlying DiffTime value?
是的。有几十个关于 monad 的教程解释了如何。它们都基于这样的想法,即您编写一个接受
DiffTime
的函数。并做某事(比如返回 IO ()
)或只返回 Answer
.所以如果你有 f :: DiffTime -> Answer
, 你写time >>= \t -> return (f t)
有些人更愿意写
time >>= (return . f)
如果你有
continue :: DiffTime -> IO ()
你有time >>= continue
或者您可能更喜欢
do
符号:do { t <- time
; continue t -- or possibly return (f t)
}
有关更多信息,请参阅有关 monad 的众多优秀教程之一。
关于haskell - 如何使用 Data.Time.Clock 在 Haskell 中获取系统时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2110419/