haskell - 如何使用 Data.Time.Clock 在 Haskell 中获取系统时间?

标签 haskell systemtime

我需要一些 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/

相关文章:

delphi - Delphi NOW 函数的结果如何受 "Adjust clock for daylight saving changes"选项的影响

Java 当前时间比我的系统时间早 2 小时

java - 系统记录器是否使用计算机资源?

haskell - 了解 'newtype' 关键字

haskell - Tree 实现 Foldable FoldMap 时 Foldr/Foldl 是免费的吗?

haskell - Haskell 中的类型

haskell - 在 Haskell 中求解方程

windows - 在 SYSTEMTIME 上执行算术运算

haskell - 这个 Haskell 函数有内存功能吗?