Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new list that adds and sums elements from an old list

Tags:

list

haskell

I have a list xxs and I need to create a new one that adds and sums elements from the old list.

Let me draw it to demonstrate:

visualization of list transformation

So, I have the list:

xxs = [("a","b", [(1,"a","b"),(2,"a","b")]), ("c","d",[(3,"a","b"),(4,"a","b")])]

My best approach so far is:

infoBasicas = [ (x,y,aux) | (x,y,_) <- xxs]
    where aux = sum [ z | (_,_,ys) <- xxs, (z,_,_) <- ys] 

Output:

[("a","b",10),("c","d",10)]

Although I’m not far away… I'm not quite there yet and would really appreciate some suggestions.

like image 631
Nomics Avatar asked Dec 15 '11 03:12

Nomics


2 Answers

The problem with you solution is that aux is the same for each element of xxs. when you write (x,y,_) <- xxs, you are throwing away the list with the numbers you want to sum. Instead, keep that list, working one element at a time, so:

infoBasicas = [(x, y, doSum innerList) | (x, y, innerList) <- xxs]

To find the sum of the innerLists, you only want the numbers, so you can throw them away. After that is done, you are left with a list of numbers, which can just be summed with the standard sum function:

doSum list = sum (fst3 list) -- There is one small error here. Can you see what it is?
fst3 (a, _, _) = a

Not that we are using fst3 here, instead of fst, as these are triples, not pairs.

like image 93
gereeter Avatar answered Nov 16 '22 02:11

gereeter


You were really close!

As the gereeter said: your main problem is that you're using the same value of aux for everything. If you change aux into a function taking the list of (Int,String,String) tuples then it should work for you.

infoBasicas = [ (x,y,aux z) | (x,y,z) <- xxs ]
  where aux xs = sum [ z | (z,_,_) <- xs ]

(I haven't really added anything to gereeter's answer except to change the form of the sample code to more closely resemble yours.)

like image 33
mange Avatar answered Nov 16 '22 01:11

mange