Haskell While Loop

September 15, 2009 at 9:48 pm | In haskell | 2 Comments

In the past week, while working on three completely unrelated Haskell projects, I have found myself in need of a while loop. So I came up with this one:

-- | For some reason Control.Monad doesn't provide a 'while'
--   function, even though it has a 'forever' function.
while :: Monad m => m Bool -> m a -> m ()
while predicate action = do
    b <- predicate
    if b then action >> while predicate action
         else return ()

Hoogle shows no functions with that type signature, and I couldn’t find anything in the documentation that seemed to fit the bill. This seems like a rather fundamental function for getting stuff done, is there something I’m missing?

EDIT: The most code-golfed version I have yet come up with is `while p a = p >>= flip when (a >> while p a)` can anyone improve on that?

2 Comments »

RSS feed for comments on this post. TrackBack URI

  1. Maybe when b $ action >> while predicate action is a little better.

  2. True. I hadn’t thought of that. flip when seems to be even more concise in the long run:

    while p a = p >>= flip when (a >> while p a)


Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.