我正在尝试在Haskell中编写一个安全的定时评估函数。 代码如下:
import System.Timeout
compute, compute' :: Int -> Int
compute i = sum [1..300000 + i]
compute' i = last $ repeat i
timedComp :: Int -> a -> IO (Maybe a)
timedComp timeLeft toCompute =
timeout timeLeft go
where
go = toCompute `seq` return toCompute
main = do
res <- timedComp 10000 (compute 0)
print res
res' <- timedComp 10000 (compute' 0)
print res'
我知道我的值只会被求值到弱头正常形式。
当我运行主函数时,输出只有一个Nothing,然后程序就卡住了。我尝试将程序编译并以多线程方式运行,但没有帮助。在GHC 7.6.3和7.8.3上都尝试过。有什么建议吗?
compute' i = last $ repeat i
经过优化后可能不需要任何分配空间。如果是这种情况,GHC 调度程序就无法切换到其他的 Haskell 线程。这是 GHC 的一个已知“限制”(好吧,是个 bug)。希望有一天 GHC 至少会在这种情况下发出警告。 - chi-fno-omit-yields
。 - Reid Barton