从类型来看,timeout :: Int -> IO a -> IO (Maybe a)
,它可以用作
import Math.NumberTheory.Primes (factorise)
import System.Timeout (timeout)
import Control.Exception (evaluate)
import Control.DeepSeq (force)
timedFact :: Int -> Integer -> IO (Maybe [(Integer, Int)])
timedFact u =
timeout u . evaluate . force . factorise
Testing:
#> timedFact 3000000 1231231231223234234273434343469494949494499437141
Nothing
(3.04 secs, 2639142736 bytes)
#> timedFact 4000000 1231231231223234234273434343469494949494499437141
Just [(1009,1),(47729236307,1),(125199345589541,1),(204202903382078984027,1)]
(3.07 secs, 2662489296 bytes)
update: as 用户2407038 在评论中说 https://stackoverflow.com/questions/32878244/haskell-functions-which-time-out/32878368?noredirect=1#comment53589782_32878368(谢谢!),
timedFact u n = timeout u (return $!! factorise n)
也有效。($!!)
来自Control.DeepSeq
也。引用文档,“在表达式 f $!! x 中,x 在函数 f 应用于它之前被完全求值” https://hackage.haskell.org/package/deepseq-1.4.1.2/docs/Control-DeepSeq.html#v:-36--33--33-.