Skip to content

Commit b93e9e1

Browse files
authored
Define groupBy via foldByKeyMap (#211)
1 parent f6a79c0 commit b93e9e1

File tree

1 file changed

+4
-7
lines changed

1 file changed

+4
-7
lines changed

src/Control/Foldl.hs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -160,8 +160,7 @@ import Data.Foldable (Foldable)
160160
import Data.Functor.Identity (Identity, runIdentity)
161161
import Data.Functor.Contravariant (Contravariant(..))
162162
import Data.HashMap.Strict (HashMap)
163-
import Data.Map.Strict (Map, alter)
164-
import Data.Maybe (fromMaybe)
163+
import Data.Map.Strict (Map)
165164
import Data.Monoid hiding ((<>))
166165
import Data.Semigroupoid (Semigroupoid)
167166
import Data.Functor.Extend (Extend(..))
@@ -979,7 +978,7 @@ foldByKeyMap f = case f of
979978
Fold (step0 :: x -> a -> x) (ini0 :: x) (end0 :: x -> b) ->
980979
let
981980
step :: Map k x -> (k,a) -> Map k x
982-
step mp (k,a) = Map.alter addToMap k mp where
981+
step !mp (k,a) = Map.alter addToMap k mp where
983982
addToMap Nothing = Just $ step0 ini0 a
984983
addToMap (Just existing) = Just $ step0 existing a
985984

@@ -1490,10 +1489,8 @@ projection function. Returns the folded result grouped as a map keyed by the
14901489
group.
14911490
14921491
-}
1493-
groupBy :: Ord g => (a -> g) -> Fold a r -> Fold a (Map g r)
1494-
groupBy grouper (Fold f i e) = Fold f' mempty (fmap e)
1495-
where
1496-
f' !m !a = alter (\o -> Just (f (fromMaybe i o) a)) (grouper a) m
1492+
groupBy :: Ord k => (a -> k) -> Fold a b -> Fold a (Map k b)
1493+
groupBy f = premap (\(!a) -> (f a, a)) . foldByKeyMap
14971494
{-# INLINABLE groupBy #-}
14981495

14991496
{-| Combine two folds into a fold over inputs for either of them.

0 commit comments

Comments
 (0)