fork download
  1. -- Converts a list of key/values into a map, aggregating values
  2. -- e.g. [(1, "one"), (2, "two"), (1, "uno")] -> Map {1: ["one", "uno"], 2: ["two"]}
  3. keyValuesToMap :: (Eq k, Ord k, Ord v) => [(k, v)] -> M.Map k [v]
  4. keyValuesToMap = M.fromList . groupValues
  5. where
  6. groupValues :: (Eq k, Ord k, Ord v) => [(k, v)] -> [(k, [v])]
  7. groupValues = map foldValues . groupBy (\(x, _) (y, _) -> x == y) . sort
  8.  
  9. -- Combines values of the same key into a list
  10. -- e.g. [(1, 2), (1, 4), (1, 5)] -> (1, [2, 4, 5])
  11. -- Precondition: the key must be the same for all values in the input list
  12. foldValues :: (Eq k, Ord k, Ord v) => [(k, v)] -> (k, [v])
  13. foldValues xs = foldr accumulateSameKeyValues (key, []) xs
  14. where
  15. key = fst . head $ xs
  16.  
  17. accumulateSameKeyValues :: (Eq k, Ord k, Ord v) => (k, v) -> (k, [v]) -> (k, [v])
  18. accumulateSameKeyValues (key1, value) (key2, values)
  19. | key1 == key2 = (key1, value:values)
  20. | otherwise = error "Cannot group values for different keys."
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
[1 of 1] Compiling Main             ( prog.hs, prog.o )

prog.hs:3:55: error:
    Not in scope: type constructor or class ‘M.Map’
    No module named ‘M’ is imported.
  |
3 | keyValuesToMap :: (Eq k, Ord k, Ord v) => [(k, v)] -> M.Map k [v]
  |                                                       ^^^^^

prog.hs:4:18: error:
    Not in scope: ‘M.fromList’
    No module named ‘M’ is imported.
  |
4 | keyValuesToMap = M.fromList . groupValues
  |                  ^^^^^^^^^^
stdout
Standard output is empty