Created
October 24, 2011 21:38
-
-
Save jbpotonnier/1310406 to your computer and use it in GitHub Desktop.
groupBy in Erlang and Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
groupBy(F, L) -> lists:foldr(fun({K,V}, D) -> dict:append(K, V, D) end , dict:new(), [ {F(X), X} || X <- L ]). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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])) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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