Skip to content

Instantly share code, notes, and snippets.

@jbpotonnier
Created October 24, 2011 21:38
Show Gist options
  • Save jbpotonnier/1310406 to your computer and use it in GitHub Desktop.
Save jbpotonnier/1310406 to your computer and use it in GitHub Desktop.
groupBy in Erlang and Haskell
groupBy(F, L) -> lists:foldr(fun({K,V}, D) -> dict:append(K, V, D) end , dict:new(), [ {F(X), X} || X <- L ]).
module GroupBy where
import Data.Map (Map)
import qualified Data.Map as Map
groupBy :: Ord b => (a -> b) -> [a] -> Map b [a]
groupBy f = foldr (\ v -> Map.insertWith (++) (f v) [v]) Map.empty
groupBy' :: Ord b => (a -> b) -> [a] -> Map b [a]
groupBy' f lst = Map.fromListWith (++) [(f x, [x]) | x <- lst]
groupBy'' :: Ord b => (a -> b) -> [a] -> Map b [a]
groupBy'' f = Map.fromListWith (++) . map (\x -> (f x, [x]))
module Main where
import GroupBy
import Test.HUnit
import qualified Data.Map as Map
main = runTestTT $ "Should group by" ~:
TestList [
groupBy length ["foo", "bar", "baz"] ~?= Map.fromList [(3, ["foo", "bar", "baz"])],
groupBy head ["foo", "bar", "baz"] ~?= Map.fromList [('b', ["bar", "baz"]), ('f', ["foo"])]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment