计划出纯粹的功能 [英] Timing out pure functions

查看:132
本文介绍了计划出纯粹的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能杀死耗时过长的纯粹计算?我试过

How can I "kill" a pure calculation which is taking too long? I tried

import System.Timeout

fact 0 = 1
fact n = n * (fact $ n - 1)

main = do maybeNum <- timeout (10 ^ 7) $ (return . fact) 99999999
          print maybeNum

但是,这不起作用。将(return。fact)99999999 替换为一个真正的IO函数,如 getLine ,并按预期工作。 / p>

However, this doesn't work. Replace the (return . fact) 99999999 with a "real" IO function like getLine and this works as expected.

推荐答案



The point is that

return (fact 999999999)

立即返回并且不触发超时。它会返回一个将在稍后评估的thunk。

immediately returns and doesn't trigger the timeout. It returns a thunk that will be evaluated later.

如果您强制评估返回值,那么

If you force evaluation of the return value,

main = do maybeNum <- timeout (10 ^ 7) $ return $! fact 99999999
          print maybeNum

它应该触发超时(如果您提供足够大的堆栈以便在堆栈溢出之前发生超时)。

it should trigger the timeout (if you provide a stack large enough so that the timeout happens before the stack overflow).

这篇关于计划出纯粹的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆