[Haskell-beginners] Iterating a monadic action with memoization
Alex
fromgmane.10.alinabi at spamgourmet.com
Sat Jan 28 20:12:12 CET 2012
Brent Yorgey <byorgey <at> seas.upenn.edu> writes:
[...]
>
>
> How about this?
>
> iterateM :: Monad m => (a -> m a) -> a -> m [a]
> iterateM f a = (a:) `liftM` (f a >>= iterateM f)
>
> -Brent
>
>
The problem with this is that it is not "lazy" in the sense that
inc :: Int -> IO Int
inc x = (print x) >> return $! x + 1
main = do
xs <- liftM (take 5) $ iterateM inc 0
print xs
will never terminate. It will keep printing all natural numbers but
it will never print the list xs. I don't quite understand why this is
so, nor do I know how to rewrite iterateM to get the desired behavior.
But I wish someone would enlighten me :-)
More information about the Beginners
mailing list