[Haskell] Monadic Loops

Peter Robinson listener at thaldyron.com
Thu Jun 17 06:58:55 EDT 2004


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 
http://haskell.org/hawiki/TailRecursive

>
> 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?
You could have a look at "Tackling the awkward squad: monadic input/output, 
concurrency, exceptions, and foreign-language calls in Haskell" (Simon Peyton 
Jones)
http://research.microsoft.com/users/simonpj/papers/marktoberdorf/
where quite a few "control structures" are described. 
Cheers,
Peter
>
> 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_
> http://www.haskell.org/onlinereport/monad.html
> if you can do with lists, then use iterate, fold etc.
> http://www.haskell.org/onlinereport/list.html
>
> best regards,


More information about the Haskell mailing list