Skip to content

stack-safe foldl #93

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 30, 2017
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
stack-safe foldl
  • Loading branch information
matthewleon committed Mar 29, 2017
commit 8d23c1773bd3cd4a403fd00044885f03da71a08e
15 changes: 9 additions & 6 deletions src/Control/Monad/List/Trans.purs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import Control.Alternative (class Alternative)
import Control.Monad.Eff.Class (class MonadEff, liftEff)
import Control.Monad.Trans.Class (class MonadTrans, lift)
import Control.MonadPlus (class MonadPlus)
import Control.Monad.Rec.Class as MR
import Control.MonadZero (class MonadZero)
import Control.Plus (class Plus)

Expand Down Expand Up @@ -204,12 +205,14 @@ foldl' f = loop where
g (Just (Tuple a as)) = (f b a) >>= (flip loop as)

-- | Fold a list from the left, accumulating the result using the specified function.
foldl :: forall f a b. Monad f => (b -> a -> b) -> b -> ListT f a -> f b
foldl f = loop where
loop b l = uncons l >>= g
where
g Nothing = pure b
g (Just (Tuple a as)) = loop (f b a) as
foldl :: forall f a b. MR.MonadRec f => (b -> a -> b) -> b -> ListT f a -> f b
foldl f b l = (MR.tailRecM2 loop) b l
where
loop :: b -> ListT f a -> f (MR.Step {a :: b, b :: ListT f a} b)
loop accum l' = uncons l' >>= g
where
g Nothing = pure (MR.Done accum)
g (Just (Tuple a as)) = pure (MR.Loop {a: f accum a, b: as})

-- | Fold a list from the left, accumulating the list of results using the specified function.
scanl :: forall f a b. Monad f => (b -> a -> b) -> b -> ListT f a -> ListT f b
Expand Down