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?
Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.