It Seemed Like a Good Idea at the Time Coding, Mostly

15Sep/092

Haskell While Loop

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?

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Filed under: haskell Leave a comment
Comments (2) Trackbacks (0)
  1. Maybe

    when b $ action &gt;&gt; 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 &gt;&gt;= flip when (a &gt;&gt; while p a)

Leave a comment


No trackbacks yet.