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

Commit 76ac5be

Browse files
committed
implement foldl without materializing value list
use a foldl-based foldMap
1 parent e424494 commit 76ac5be

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,7 +43,7 @@ module Data.Map
4343
import Prelude
4444

4545
import Data.Eq (class Eq1)
46-
import Data.Foldable (foldl, foldMap, foldr, class Foldable)
46+
import Data.Foldable (foldl, foldMap, foldr, foldMapDefaultL, class Foldable)
4747
import Data.FoldableWithIndex (class FoldableWithIndex)
4848
import Data.FunctorWithIndex (class FunctorWithIndex, mapWithIndex)
4949
import Data.List (List(..), (:), length, nub)
@@ -99,9 +99,21 @@ instance functorWithIndexMap :: FunctorWithIndex k (Map k) where
9999
mapWithIndex f (Three left k1 v1 mid k2 v2 right) = Three (mapWithIndex f left) k1 (f k1 v1) (mapWithIndex f mid) k2 (f k2 v2) (mapWithIndex f right)
100100

101101
instance foldableMap :: Foldable (Map k) where
102-
foldl f z m = foldl f z (values m)
103-
foldr f z m = foldr f z (values m)
104-
foldMap f m = foldMap f (values m)
102+
foldl f z m = go z (m : Nil)
103+
where
104+
go acc Nil = acc
105+
go acc (hd : tl) = case hd of
106+
Leaf -> go acc tl
107+
Two Leaf _ v Leaf ->
108+
go (f acc v) tl
109+
Two Leaf _ v right ->
110+
go (f acc v) (right : tl)
111+
Two left k v right ->
112+
go acc (left : singleton k v : right : tl)
113+
Three left k1 v1 mid k2 v2 right ->
114+
go acc (left : singleton k1 v1 : mid : singleton k2 v2 : right : tl)
115+
foldr f z m = foldr f z (values m)
116+
foldMap = foldMapDefaultL
105117

106118
instance foldableWithIndexMap :: FoldableWithIndex k (Map k) where
107119
foldlWithIndex f z m = foldl (uncurry <<< (flip f)) z $ asList $ toUnfoldable m

0 commit comments

Comments
 (0)