module Algo where import Data.List import qualified Data.Map as M -- Group data from a list of (key,value) pairs -- to a Map of key->[value] lists. groupFirst :: (Ord k) => [(k, v)] -> M.Map k [v] groupFirst = M.map reverse . groupFirst' -- Group data from a list of (key,value) pairs -- to a Map of key->[value] lists. -- The values are present in reverse order. groupFirst' :: (Ord k) => [(k, v)] -> M.Map k [v] groupFirst' = foldl' add M.empty where add map_ (key, value) = M.insertWith prepend key [value] map_ prepend (x:_) xs = x:xs -- prepend _ _ = impossible