![](/img/trans.png)
[英]Why Data.Time.Clock provides DiffTime and NominalDiffTime?
[英]How to get system time in Haskell using Data.Time.Clock?
我需要一些Int
用作隨機數生成的種子,所以我想使用系統時間作為種子的舊技巧。
所以我嘗試使用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
但我找不到它的逆。
有可能以某種方式展開IO並獲取基礎DiffTime值嗎?
是。 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上許多精細的tutorals之一。
如果您計划使用標准的System.Random
模塊進行隨機數生成,那么已經有一個生成器,其中為您初始化了一個與時間相關的種子:您可以通過調用getStdGen :: IO StdGen
來獲取它。 (當然,您仍然需要問題(a)部分的答案才能使用結果。)
這個功能並不是OP要求的。 但它很有用:
λ: import Data.Time.Clock
λ: let getSeconds = getCurrentTime >>= return . fromRational . toRational . utctDayTime
λ: :i getSeconds
getSeconds :: IO Double -- Defined at <interactive>:56:5
λ: getSeconds
57577.607162
λ: getSeconds
57578.902397
λ: getSeconds
57580.387334
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.