Calculating the sum of values in a list of tuples in haskell

13,364

Solution 1

foldl (\a (x, y, z) -> a + y*z) 0 [("A", 100, 2), ("B", 50, 3)]

This expands to: ((0 + 100 * 2) + 50 * 3)

Solution 2

λ> sum $ map (\(_,y,z) -> y*z ) [("A",100,2),("B",50,3)]
350

UPD: trying to add some explanation

So, we have a tuple ("A",100,2). We need to get product of second and third element? With anonymous function.

λ> (\(x,y,z) -> y*z) ("A",100,2)
200

X is unusable here, so we can pass it

λ> (\(_,y,z) -> y*z) ("A",100,2)
200

Then we should apply that function to list of such tuples with map.

λ> map (\(_,y,z) -> y*z) [("A",100,2),("B",50,3)]
[200,150]

And last thing is finding sum of [Int] with sum.

λ> sum (map (\(_,y,z) -> y*z) [("A",100,2),("B",50,3)])
350

We can use $(function application) instead of parentheses.

λ> sum $ map (\(_,y,z) -> y*z) [("A",100,2),("B",50,3)]
350

Done.

Solution 3

Using a list comprehension:

*Main> let tuples = [("A",100,2),("B",50,3)]
*Main> sum [x*y | (_,x,y) <- tuples]
350
Share:
13,364
Roy
Author by

Roy

Updated on June 05, 2022

Comments

  • Roy
    Roy almost 2 years

    I am having two tuples in a list. For example: [("A",100,2),("B",50,3)]. I need to multiply the second and third elements of each and every tuple, sum the totals and show it. For example:

    100* 2 = 200 (add this to a variable),
    50* 3 = 150 (add this to the same variable),
    Grant total = 350 (I want to display only this).

    If any one can suggest me a solution for this it would be a great help for me.