Jonathan
Jonathan

Reputation: 11331

How can I sum a list of tuples in Haskell?

This is a super simple question, but I can't seem to find the answer. Say I have a list of tuples in Haskell,

myList = [("foo", 2), ("bar", 4), ("foo", 6), ("bar", 1)]

and I want to group them by their first elements and sum them on their second, how would I do that?

This example would output [("foo", 8), ("bar", 5)]

Upvotes: 1

Views: 295

Answers (1)

Zeta
Zeta

Reputation: 105975

It heavily depends on whether your key (the first element in your tuple) is Ord or only Eq. If its only in Eq, then a partition-based approach is fine:

import Data.List (partition)

sumByKey :: (Eq k, Num v) => [(k, v)] -> [(k, v)]
sumByKey []         = []
sumByKey ((k,v):xs) = (k,v + sum vs) : sumByKey bs
  where
    vs       = map snd ks
    (ks, bs) = partition ((k ==) . fst) xs

However, if you have Ord at hand and are fine with external dependencies, then Map can make the code a lot easier:

import Data.Map.Strict

sumByKey :: (Ord k, Num v) => [(k, v)] -> [(k, v)]
sumByKey = toList . fromListWith (+)

Upvotes: 5

Related Questions