
On Sat, Jan 28, 2012 at 8:12 PM, Alex
Brent Yorgey
writes: iterateM :: Monad m => (a -> m a) -> a -> m [a] iterateM f a = (a:) `liftM` (f a >>= iterateM f) The problem with this is that it is not "lazy" in the sense that
[IO example]
What do you mean it's not lazy ? look :
import Control.Monad import Control.Monad.State.Lazy
inc x = modify (+x) >> get
main = do let (pows,_) = runState (liftM (take 5) $ iterateM inc 1) $ 0 print pows
.... In other words, the lazyness is not in iterateM, it's in the monad (you can use unsafeInterleaveIO to get lazy IO but that's... unsafe).
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 :-)
Basically IO is strict, if it wasn't, you wouldn't always get the correct order for your side-effects except when explicit data dependency forced it (unsafeInterleaveIO is a way to relax this when you don't care exactly when your side-effect happens, for instance lazy IO take the stance that you don't need to know exactly when your file will be read, so you might as well defer its reading until the content is really needed). -- Jedaï