Haskell函数超时

时间:2015-10-01 01:48:38

标签: multithreading haskell io timeout

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 = ?

试图理解如何编写因使用过后超时的因子的包装函数。如果成功则返回RetType,否则返回Integer(传入的内容)

我是Haskell的新手。我知道超时需要在IO Monad工作,但我无法撤回相应的结果。 (注意:我没有和Either结婚。Maybe RetType也没关系。

感谢您的帮助

1 个答案:

答案 0 :(得分:6)

查看类型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)

更新: user2407038 says in the comments(谢谢!),

timedFact u n = timeout u (return $!! factorise n)

也有效。 ($!!)也来自Control.DeepSeq。引用文档"In the expression f $!! x, x is fully evaluated before the function f is applied to it"