Skip to content

Commit 6d1c863

Browse files
authored
Merge pull request #118 from matthewleon/foldr'
foldr': lazy right folds
2 parents b7103d8 + f678fb1 commit 6d1c863

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

src/Data/List/Lazy.purs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ module Data.List.Lazy
8686
, transpose
8787

8888
, foldM
89+
, foldrLazy
8990

9091
, module Exports
9192
) where
@@ -716,3 +717,11 @@ foldM f a xs =
716717
Nothing -> pure a
717718
Just { head: b, tail: bs } ->
718719
f a b >>= \a' -> foldM f a' bs
720+
721+
-- | Perform a right fold lazily
722+
foldrLazy :: forall a b. Z.Lazy b => (a -> b -> b) -> b -> List a -> b
723+
foldrLazy op z = go
724+
where
725+
go xs = case step xs of
726+
Cons x xs' -> Z.defer \_ -> x `op` go xs'
727+
Nil -> z

test/Test/Data/List/Lazy.purs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import Control.Monad.Eff (Eff)
77
import Control.Monad.Eff.Console (CONSOLE, log)
88

99
import Data.Lazy as Z
10-
import Data.List.Lazy (List, nil, cons, foldl, foldr, foldMap, singleton, transpose, take, iterate, filter, uncons, foldM, range, unzip, zip, length, zipWithA, replicate, repeat, zipWith, intersectBy, intersect, deleteBy, delete, unionBy, union, nubBy, nub, groupBy, group, partition, span, dropWhile, drop, takeWhile, slice, catMaybes, mapMaybe, filterM, concat, concatMap, reverse, alterAt, modifyAt, updateAt, deleteAt, insertAt, findLastIndex, findIndex, elemLastIndex, elemIndex, init, tail, last, head, insertBy, insert, snoc, null, replicateM, fromFoldable, (:), (\\), (!!))
10+
import Data.List.Lazy (List, nil, cons, foldl, foldr, foldMap, singleton, transpose, take, iterate, filter, uncons, foldM, foldrLazy, range, unzip, zip, length, zipWithA, replicate, repeat, zipWith, intersectBy, intersect, deleteBy, delete, unionBy, union, nubBy, nub, groupBy, group, partition, span, dropWhile, drop, takeWhile, slice, catMaybes, mapMaybe, filterM, concat, concatMap, reverse, alterAt, modifyAt, updateAt, deleteAt, insertAt, findLastIndex, findIndex, elemLastIndex, elemIndex, init, tail, last, head, insertBy, insert, snoc, null, replicateM, fromFoldable, (:), (\\), (!!))
1111
import Data.List.Lazy.NonEmpty as NEL
1212
import Data.Maybe (Maybe(..), isNothing, fromJust)
1313
import Data.Monoid.Additive (Additive(..))
@@ -339,6 +339,10 @@ testListLazy = do
339339
f acc x = if x >= 10 then Nothing else Just (cons 0 acc)
340340
in foldM f nil infs == Nothing
341341

342+
log "foldrLazy should work ok on infinite lists"
343+
assert let infs = iterate (_ + 1) 1
344+
infs' = foldrLazy cons nil infs
345+
in take 1000 infs == take 1000 infs'
342346

343347
log "can find the first 10 primes using lazy lists"
344348
let eratos :: List Int -> List Int

0 commit comments

Comments
 (0)