The timeout function in System.Timeout sometimes fails to halt an infinite computation.
For example,
timeout 1000 $ print $ length [0..]
returns Nothing
as expected because the timeout interrupts the infinite computation. But
timeout 1000 $ print $ length $ cycle [1,2,3]
loops forever.
This is on a Mac, using ghc or ghci 8.6.4.
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.
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
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>>>
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With