문제

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

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)

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).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top