import Math.NumberTheory.Primes (factorise)
import System.Timeout (timeout)
import Control.Monad (liftM)
type RetType = [(Integer, Int)] -- factorise's return type
-- proposed function
timedFact :: Integer -> Integer -> Either RetType Integer
timedFact u n = ?
试着理解如何为factorise编写一个包装器函数,该函数在使用后会超时。如果成功,则返回RetType
,否则返回Integer
(传入的内容)
我对Haskell有点陌生。我理解超时需要在IO
Monad工作,但我很难收回适当的结果。(注:我没有和Either
结婚。Maybe RetType
也可以)。
感谢您的帮助
看看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
测试:
#> 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 user2407038在评论中说(谢谢!),
timedFact u n = timeout u (return $!! factorise n)
同样适用。($!!)
也来自Control.DeepSeq
。要引用文档,"在表达式f $!!