Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum a list of tuples

Tags:

tuples

scala

sum

Given the following list of tuples...

val list = List((1, 2), (1, 2), (1, 2))

... how do I sum all the values and obtain a single tuple like this?

(3, 6)
like image 542
j3d Avatar asked May 10 '15 17:05

j3d


People also ask

How do you sum a list of tuples in Python?

To find a sum of the tuple in Python, use the sum() method. Define a tuple with number values and pass the tuple as a parameter to the sum() function; in return, you will get the sum of tuple items.

Can you sum tuples in Python?

The built-in sum() function in Python is used to return the sum of an iterable. To get the sum total of a tuple of numbers, you can pass the tuple as an argument to the sum() function.

How do you sum two tuples in Python?

To add two tuples element-wise:Use the zip function to get an iterable of tuples with the corresponding items. Use a list comprehension to iterate over the iterable. On each iteration, pass the tuple to the sum() function.

How do you sum a list in Python?

Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers. start : this start is added to the sum of numbers in the iterable.


2 Answers

Using the foldLeft method. Please look at the scaladoc for more information.

scala> val list = List((1, 2), (1, 2), (1, 2))
list: List[(Int, Int)] = List((1,2), (1,2), (1,2))

scala> list.foldLeft((0, 0)) { case ((accA, accB), (a, b)) => (accA + a, accB + b) }
res0: (Int, Int) = (3,6)

Using unzip. Not as efficient as the above solution. Perhaps more readable.

scala> list.unzip match { case (l1, l2) => (l1.sum, l2.sum) }
res1: (Int, Int) = (3,6) 
like image 86
Lomig Mégard Avatar answered Sep 30 '22 16:09

Lomig Mégard


You can solve this using Monoid.combineAll from the cats library:

import cats.instances.int._ // For monoid instances for `Int`
import cats.instances.tuple._  // for Monoid instance for `Tuple2`
import cats.Monoid.combineAll

  def main(args: Array[String]): Unit = {

    val list = List((1, 2), (1, 2), (1, 2))

    val res = combineAll(list)

    println(res)
    // Displays
    // (3, 6)
  }

You can see more about this in the cats documentation or Scala with Cats.

like image 38
Valy Dia Avatar answered Sep 30 '22 17:09

Valy Dia