[Haskell] Monadic Loops
waldmann at imn.htwk-leipzig.de
Thu Jun 17 06:39:28 EDT 2004
> while test body = do
> (cond,res) <- body
> if (test cond) then do rs <- while test body
> return (res:rs)
> else return [res]
do you need the monad here? what monad is it?
the problem could to be that the "return $ res: rs"
can happen only after it is certain
that "while test body" succeeds.
so you won't even see the very first cons cell
before the last one is evaluated.
could you produce a (lazy) list of results instead?
the garbage collector might be able to collect
the list cells that are no longer needed
possibly, a lazy state monad would help
(if the computation of "while test body" cannot fail)
> Is there a better way to implement (possibly infinite) loops in Haskell?
generally, don't program your own recursions -
use pre-defined combinators instead.
(I like to think of this as a "higher analogon"
of "don't use goto - use block structures" from imperative programming)
if you need monads, have a look at sequence, sequence_, mapM, mapM_
if you can do with lists, then use iterate, fold etc.
-- Johannes Waldmann, Tel/Fax: (0341) 3076 6479 / 6480 --
------ http://www.imn.htwk-leipzig.de/~waldmann/ ---------
More information about the Haskell