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:
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.
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 innerList
s, 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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With