[Haskell] Monadic Loops
gustavov at ucse.edu.ar
Thu Jun 17 09:15:08 EDT 2004
An interesting paper on Monads and Recursion is
"Merging Monads and Folds for Functional Programming"
Erik Meijer and Johan Jeuring
Peter Robinson said:
> On Thursday 17 June 2004 12:39, Johannes Waldmann wrote:
>> > 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.
> See also
>> 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
> You could have a look at "Tackling the awkward squad: monadic
> input/output, concurrency, exceptions, and foreign-language calls in
> Haskell" (Simon Peyton Jones)
> where quite a few "control structures" are described.
>> 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
>> if you need monads, have a look at sequence, sequence_, mapM, mapM_
>> if you can do with lists, then use iterate, fold etc.
>> best regards,
> Haskell mailing list
> Haskell at haskell.org
More information about the Haskell