MonadRandom-computation that does not terminate

Hi, I'm having difficulties with this function I wrote: iterateR :: (MonadRandom m) => (a -> m a) -> a -> m [a] iterateR g s = do s' <- g s return (s:) `ap` iterateR g s' I'm running the computation with evalRandIO and surprisingly the first call of main in ghci succeeds, but the second does not terminate. Reproducible. Any clues what I'm doing wrong here? Thanks in advance, Tim

On 11/01/11 23:19, Tim Baumgartner wrote:
Hi,
I'm having difficulties with this function I wrote:
iterateR :: (MonadRandom m) => (a -> m a) -> a -> m [a] iterateR g s = do s' <- g s return (s:) `ap` iterateR g s'
I'm running the computation with evalRandIO and surprisingly the first call of main in ghci succeeds, but the second does not terminate. Reproducible. Any clues what I'm doing wrong here?
If we unfold ap we get: iterateR g s = do s' <- g s f <- return (s:) x <- iterateR g s' return (f x) What happens here depends on exactly how the monad is defined, but for many monads that will form an infinite loop that prevents a value being returned. In the case of RandT from MonadRandom, it is not possible to execute the action after the iterateR call finishes without knowing the final state from the call, which requires evaluating the infinite loop of monadic actions. Does that help? Thanks, Neil.

2011/1/12 Neil Brown
On 11/01/11 23:19, Tim Baumgartner wrote:
Hi,
I'm having difficulties with this function I wrote:
iterateR :: (MonadRandom m) => (a -> m a) -> a -> m [a] iterateR g s = do s' <- g s return (s:) `ap` iterateR g s'
I'm running the computation with evalRandIO and surprisingly the first call of main in ghci succeeds, but the second does not terminate. Reproducible. Any clues what I'm doing wrong here?
If we unfold ap we get:
iterateR g s = do s' <- g s f <- return (s:) x <- iterateR g s' return (f x)
What happens here depends on exactly how the monad is defined, but for many monads that will form an infinite loop that prevents a value being returned. In the case of RandT from MonadRandom, it is not possible to execute the action after the iterateR call finishes without knowing the final state from the call, which requires evaluating the infinite loop of monadic actions. Does that help?
Yes, this helps definitely. So if I understand you right, the infinite loop was not entered immediately because of lazyness? That's funny somehow. Thanks a lot

On Wed, Jan 12, 2011 at 12:19:50AM +0100, Tim Baumgartner wrote:
Hi,
I'm having difficulties with this function I wrote:
iterateR :: (MonadRandom m) => (a -> m a) -> a -> m [a] iterateR g s = do s' <- g s return (s:) `ap` iterateR g s'
As a side note, the MonadRandom constraint is funny, since this function doesn't depend on any sort of randomness. You may consider changing the constraint to simply Monad m => ... -Brent
participants (3)
-
Brent Yorgey
-
Neil Brown
-
Tim Baumgartner