Haskell While Loop
September 15, 2009 at 9:48 pm | In haskell | 2 CommentsIn 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
Leave a comment
Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.
Maybe
when b $ action >> while predicate actionis a little better.Comment by brian — September 15, 2009 #
True. I hadn’t thought of that.
flip whenseems to be even more concise in the long run:while p a = p >>= flip when (a >> while p a)Comment by Will Donnelly — September 15, 2009 #