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

Commit 2f4a2fc

Browse files
committed
implement foldl without materializing value list
use a foldl-based foldMap
1 parent d8d28ac commit 2f4a2fc

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

src/Data/Map.purs

Lines changed: 13 additions & 7 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,15 +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 = go acc (m : Nil)
102+
foldl f z m = go z (m : Nil)
103+
where
103104
go acc Nil = acc
104105
go acc (hd : tl) = case hd of
105106
Leaf -> go acc tl
106-
Two left _ v right ->
107-
go (f acc k) (left : right : tl)
108-
109-
foldr f z m = foldr f z (values m)
110-
foldMap f m = foldMap f (values m)
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
111117

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

0 commit comments

Comments
 (0)