Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use foldByKeyMap to define groupBy #211

Merged
merged 1 commit into from
Aug 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 4 additions & 7 deletions src/Control/Foldl.hs
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,7 @@ import Data.Foldable (Foldable)
import Data.Functor.Identity (Identity, runIdentity)
import Data.Functor.Contravariant (Contravariant(..))
import Data.HashMap.Strict (HashMap)
import Data.Map.Strict (Map, alter)
import Data.Maybe (fromMaybe)
import Data.Map.Strict (Map)
import Data.Monoid hiding ((<>))
import Data.Semigroupoid (Semigroupoid)
import Data.Functor.Extend (Extend(..))
Expand Down Expand Up @@ -979,7 +978,7 @@ foldByKeyMap f = case f of
Fold (step0 :: x -> a -> x) (ini0 :: x) (end0 :: x -> b) ->
let
step :: Map k x -> (k,a) -> Map k x
step mp (k,a) = Map.alter addToMap k mp where
step !mp (k,a) = Map.alter addToMap k mp where
addToMap Nothing = Just $ step0 ini0 a
addToMap (Just existing) = Just $ step0 existing a

Expand Down Expand Up @@ -1490,10 +1489,8 @@ projection function. Returns the folded result grouped as a map keyed by the
group.

-}
groupBy :: Ord g => (a -> g) -> Fold a r -> Fold a (Map g r)
groupBy grouper (Fold f i e) = Fold f' mempty (fmap e)
where
f' !m !a = alter (\o -> Just (f (fromMaybe i o) a)) (grouper a) m
groupBy :: Ord k => (a -> k) -> Fold a b -> Fold a (Map k b)
groupBy f = premap (\(!a) -> (f a, a)) . foldByKeyMap
{-# INLINABLE groupBy #-}

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