Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the Haskell timeout function (in System.Timeout) to halt runaway computations?

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.

like image 221
Peter Schachte Avatar asked Mar 25 '19 11:03

Peter Schachte


1 Answers

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:

  • How can I stop infinite evaluation in GHCi?
like image 114
Will Ness Avatar answered Oct 21 '22 22:10

Will Ness