The following function executes each action from the list until a predicate returns True
. I have a feeling that this function can be rewritten using fold
and without the do
construct but I don't know how.
execUntil :: (Eq a, Monad m) => [m a] -> (a -> Bool) -> m ()
execUntil [] p = return ()
execUntil (a:as) p = do
r <- a
if p r then return () else execUntil as p
foldM
is a left fold, I don't think you can use it for this. You also can't use a non-monadic fold.execUntil
is calledwhileM
inControl.Monad.Extra
andControl.Monad.Loops
, implemented withwhen
rather thanif/then/else
but otherwise the same. It will still do recursion under the hood but there's no way around this. \$\endgroup\$