Skip to content
This repository was archived by the owner on Oct 4, 2020. It is now read-only.

Commit 269c0a5

Browse files
committed
right folds without materializing intermediate list
1 parent 8090ce4 commit 269c0a5

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/Data/Map.purs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,8 @@ module Data.Map
4343
import Prelude
4444

4545
import Data.Eq (class Eq1)
46-
import Data.Foldable (foldl, foldr, foldMapDefaultL, class Foldable)
47-
import Data.FoldableWithIndex (class FoldableWithIndex, foldlWithIndex, foldMapWithIndexDefaultL)
46+
import Data.Foldable (foldl, foldMapDefaultL, class Foldable)
47+
import Data.FoldableWithIndex (class FoldableWithIndex, foldlWithIndex, foldrWithIndex, foldMapWithIndexDefaultL)
4848
import Data.FunctorWithIndex (class FunctorWithIndex, mapWithIndex)
4949
import Data.List (List(..), (:), length, nub)
5050
import Data.List.Lazy as LL
@@ -100,7 +100,7 @@ instance functorWithIndexMap :: FunctorWithIndex k (Map k) where
100100

101101
instance foldableMap :: Foldable (Map k) where
102102
foldl f = foldlWithIndex (const f)
103-
foldr f z m = foldr f z (values m)
103+
foldr f = foldrWithIndex (const f)
104104
foldMap = foldMapDefaultL
105105

106106
instance foldableWithIndexMap :: FoldableWithIndex k (Map k) where
@@ -117,7 +117,19 @@ instance foldableWithIndexMap :: FoldableWithIndex k (Map k) where
117117
go acc (left : singleton k v : right : tl)
118118
Three left k1 v1 mid k2 v2 right ->
119119
go acc (left : singleton k1 v1 : mid : singleton k2 v2 : right : tl)
120-
foldrWithIndex f z m = foldr (uncurry f) z $ asList $ toUnfoldable m
120+
foldrWithIndex f z m = go (m : Nil)
121+
where
122+
go Nil = z
123+
go (hd : tl) = case hd of
124+
Leaf -> go tl
125+
Two Leaf k v Leaf ->
126+
f k v $ go tl
127+
Two Leaf k v right ->
128+
f k v $ go $ right : tl
129+
Two left k v right ->
130+
go $ left : singleton k v : right : tl
131+
Three left k1 v1 mid k2 v2 right ->
132+
go $ left : singleton k1 v1 : mid : singleton k2 v2 : right : tl
121133
foldMapWithIndex = foldMapWithIndexDefaultL
122134

123135
asList :: forall k v. List (Tuple k v) -> List (Tuple k v)

0 commit comments

Comments
 (0)