I want to make a function that takes a list eg
[('A',3), ('B',2), ('C',2), ('A',5), ('C',3), ('C',2)]
and then adds the numbers together when the letter is the same. So the above input would produce
[('A',8), ('B',2), ('C',7)].
Could someone please just give me an idea of how to approach this, I’d like to try and do as much as possible myself!
You can use
Data.Map‘sfromListWithto construct a map that has the summed values. It’s type is this:It takes a list of pairs (as you described) as the first arg, if it sees a duplicate, it uses some function (the first arg), to combine the original value with a new one. From there, you can convert this map back into a list of pairs (also a function in Data.Map).
You could do this with pure lists, but it probably won’t be that effecient, as you’ll be constructing a new list (or portions of it) quite often.