问题描述
System.Timeout中的超时功能有时无法停止无限计算.
The timeout function in System.Timeout sometimes fails to halt an infinite computation.
例如,
timeout 1000 $ print $ length [0..]
按预期返回Nothing
,因为超时中断了无限计算.但是
returns Nothing
as expected because the timeout interrupts the infinite computation. But
timeout 1000 $ print $ length $ cycle [1,2,3]
永远循环.
这是在Mac上,使用ghc或ghci 8.6.4.
This is on a Mac, using ghc or ghci 8.6.4.
我希望第二个示例的行为与第一个示例相同,在1毫秒后中断无限计算并返回Nothing
.而是,第二个示例挂起.
I expect the second example to behave like the first, interrupting the infinite computation after 1 millisecond and returning Nothing
. Instead, the second example hangs.
推荐答案
您可以使用自己的cycle
的非共享实现:
You can use your own, non-sharing implementation of cycle
:
> _Y g = g (_Y g)
_Y :: (t -> t) -> t
> take 10 . _Y $ ([1,2,3] ++)
[1,2,3,1,2,3,1,2,3,1]
it :: Num a => [a]
> timeout 100000 . print . length . _Y $ ([1,2,3] ++)
Nothing
it :: Maybe ()
(0.11 secs, 152470624 bytes)
_Y
当然会分配一个无限的,不断增长的列表,与共享cycle
不同,共享cycle
等效于fix ([1,2,3] ++)
会在内存中创建实际的循环列表:
_Y
will of course allocate an infinite, growing list, unlike the sharing cycle
which is equivalent to fix ([1,2,3] ++)
which creates an actual cyclic list in memory:
> timeout 100000 . print . length . fix $ ([1,2,3] ++)
<<<hangs>>>
另请参阅:
这篇关于如何使用Haskell超时功能(在System.Timeout中)停止失控计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!