[Haskell] Monadic Loops

Ben.Yu at combined.com Ben.Yu at combined.com
Thu Jun 17 11:44:21 EDT 2004

You may want to try tail-recursion version

while test body = liftM reverse $ loop []
  loop acc = do
    (cond,res) <- body
    (if test cond then loop else return) (res:acc)


                      Vivian McPhail                                                                                                       
                      <vivian.mcphail at parad        To:       haskell at haskell.org                                                           
                      ise.net.nz>                  cc:                                                                                     
                      Sent by:                     Subject:  [Haskell] Monadic Loops                                                       
                      haskell-bounces at haske                                                                                                
                      06/17/2004 04:16 AM                                                                                                  


I've implemented a Neural Net simulator which needs to repeat a training
loop many times. For this I used a while function:
while test body = do
                  (cond,res) <- body
                  if (test cond) then do rs <- while test body
                                      return (res:rs)
                  else return [res]

However, when I run the program, the interpreter falls over after a few
thousand iterations, running out of space. I think that this is because the
Monadic implementation of the while loop actually nests functions of type
(a -> M b) and there is a maximum ?stack size.

Is there a better way to implement (possibly infinite) loops in Haskell?
Haskell mailing list
Haskell at haskell.org

This message is intended only for the addressee and may contain information
that is confidential or privileged. Unauthorized use is strictly prohibited
and may be unlawful. If you are not the intended recipient, or the person
responsible for delivering to the intended recipient, you should not read,
copy, disclose or otherwise use this message, except for the purpose of
delivery to the addressee. If you have received this email in error, please
delete and advise us immediately.

More information about the Haskell mailing list