@@ -9,7 +9,9 @@ module Control.Monad.List.Trans
9
9
, dropWhile
10
10
, filter
11
11
, foldl
12
+ , foldlRec
12
13
, foldl'
14
+ , foldlRec'
13
15
, fromEffect
14
16
, head
15
17
, iterate
@@ -39,6 +41,7 @@ import Control.Alternative (class Alternative)
39
41
import Control.Monad.Eff.Class (class MonadEff , liftEff )
40
42
import Control.Monad.Trans.Class (class MonadTrans , lift )
41
43
import Control.MonadPlus (class MonadPlus )
44
+ import Control.Monad.Rec.Class as MR
42
45
import Control.MonadZero (class MonadZero )
43
46
import Control.Plus (class Plus )
44
47
@@ -203,6 +206,15 @@ foldl' f = loop where
203
206
g Nothing = pure b
204
207
g (Just (Tuple a as)) = (f b a) >>= (flip loop as)
205
208
209
+ -- | Fold a list from the left, accumulating the result (effectfully) using the specified function.
210
+ -- | Uses tail call optimization.
211
+ foldlRec' :: forall f a b . MR.MonadRec f => (b -> a -> f b ) -> b -> ListT f a -> f b
212
+ foldlRec' f = MR .tailRecM2 loop where
213
+ loop b l = uncons l >>= g
214
+ where
215
+ g Nothing = pure (MR.Done b)
216
+ g (Just (Tuple a as)) = (f b a) >>= \b' -> pure (MR.Loop {a: b', b: as})
217
+
206
218
-- | Fold a list from the left, accumulating the result using the specified function.
207
219
foldl :: forall f a b . Monad f => (b -> a -> b ) -> b -> ListT f a -> f b
208
220
foldl f = loop where
@@ -211,6 +223,16 @@ foldl f = loop where
211
223
g Nothing = pure b
212
224
g (Just (Tuple a as)) = loop (f b a) as
213
225
226
+ -- | Fold a list from the left, accumulating the result using the specified function.
227
+ -- | Uses tail call optimization.
228
+ foldlRec :: forall f a b . MR.MonadRec f => (b -> a -> b ) -> b -> ListT f a -> f b
229
+ foldlRec f = MR .tailRecM2 loop
230
+ where
231
+ loop b l = uncons l >>= g
232
+ where
233
+ g Nothing = pure (MR.Done b)
234
+ g (Just (Tuple a as)) = pure (MR.Loop {a: f b a, b: as})
235
+
214
236
-- | Fold a list from the left, accumulating the list of results using the specified function.
215
237
scanl :: forall f a b . Monad f => (b -> a -> b ) -> b -> ListT f a -> ListT f b
216
238
scanl f b l = unfold g (Tuple b l)
0 commit comments