Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lists - combining pairs

Tags:

list

haskell

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!

like image 645
L.R88 Avatar asked Jan 08 '12 03:01

L.R88


People also ask

What is a paired list?

A list is a combination of pairs that creates a linked list. More precisely, a list is either the empty list null, or it is a pair whose first element is a list element and whose second element is a list.

How do you pair elements in a list in python?

To join pairs of list elements in Python: Use the range() class with a step argument or 2. Use a list comprehension to iterate over the range of indexes. On each iteration, join the list item at the current index with the item at the next index.

How do I combine two lists of elements?

Join / Merge two lists in python using + operator In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.

Is every list a pair in scheme?

Yes! Lists: A list is just a special type of pair.


1 Answers

You can use Data.Map's fromListWith to construct a map that has the summed values. It's type is this:

fromListWith :: Ord k => (a -> a -> a) -> [(k, a)] -> Map k a

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.

like image 188
Adam Wagner Avatar answered Sep 27 '22 17:09

Adam Wagner