Skip to content

Commit d808596

Browse files
authored
Merge pull request ndmitchell#59 from infinity0/master
Add whileJustM, untilJustM to Control.Monad.Extra
2 parents 5056b92 + b8512cd commit d808596

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

src/Control/Monad/Extra.hs

+21-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ module Control.Monad.Extra(
1111
unit,
1212
maybeM, fromMaybeM, eitherM,
1313
-- * Loops
14-
loop, loopM, whileM,
14+
loop, loopM, whileM, whileJustM, untilJustM,
1515
-- * Lists
1616
partitionM, concatMapM, concatForM, mconcatMapM, mapMaybeM, findM, firstJustM,
1717
fold1M, fold1M_,
@@ -160,6 +160,26 @@ whileM act = do
160160
b <- act
161161
when b $ whileM act
162162

163+
-- | Keep running an operation until it becomes a 'Nothing', accumulating the
164+
-- monoid results inside the 'Just's as the result of the overall loop.
165+
whileJustM :: (Monad m, Monoid a) => m (Maybe a) -> m a
166+
whileJustM act = go mempty
167+
where
168+
go accum = do
169+
res <- act
170+
case res of
171+
Nothing -> pure accum
172+
Just r -> go $! (accum <> r) -- strict apply, otherwise space leaks
173+
174+
-- | Keep running an operation until it becomes a 'Just', then return the value
175+
-- inside the 'Just' as the result of the overall loop.
176+
untilJustM :: Monad m => m (Maybe a) -> m a
177+
untilJustM act = do
178+
res <- act
179+
case res of
180+
Just r -> pure r
181+
Nothing -> untilJustM act
182+
163183
-- Booleans
164184

165185
-- | Like 'when', but where the test can be monadic.

src/Extra.hs

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ module Extra {-# DEPRECATED "This module is provided as documentation of all new
1414
Partial, retry, retryBool, errorWithoutStackTrace, showException, stringException, errorIO, ignore, catch_, handle_, try_, catchJust_, handleJust_, tryJust_, catchBool, handleBool, tryBool,
1515
-- * Control.Monad.Extra
1616
-- | Extra functions available in @"Control.Monad.Extra"@.
17-
whenJust, whenJustM, whenMaybe, whenMaybeM, unit, maybeM, fromMaybeM, eitherM, loop, loopM, whileM, partitionM, concatMapM, concatForM, mconcatMapM, mapMaybeM, findM, firstJustM, fold1M, fold1M_, whenM, unlessM, ifM, notM, (||^), (&&^), orM, andM, anyM, allM,
17+
whenJust, whenJustM, whenMaybe, whenMaybeM, unit, maybeM, fromMaybeM, eitherM, loop, loopM, whileM, whileJustM, untilJustM, partitionM, concatMapM, concatForM, mconcatMapM, mapMaybeM, findM, firstJustM, fold1M, fold1M_, whenM, unlessM, ifM, notM, (||^), (&&^), orM, andM, anyM, allM,
1818
-- * Data.Either.Extra
1919
-- | Extra functions available in @"Data.Either.Extra"@.
2020
fromLeft, fromRight, fromEither, fromLeft', fromRight', eitherToMaybe, maybeToEither, mapLeft, mapRight,

0 commit comments

Comments
 (0)