Add two tuples containing simple elements in Scala

+1 for the the Scalaz answer :-)

If you want a very simple version of it you could define an implicit class like:

implicit class TuppleAdd(t: (Int, Int)) {
  def +(p: (Int, Int)) = (p._1 + t._1, p._2 + t._2)
}

(1, 1) + (2, 2) == (3, 3)

// update1, more generic version for numbers:

So this is the simplest version, defined only for Ints, we could generify it for all numeric values using Scala's Numeric:

implicit class Tupple2Add[A : Numeric, B : Numeric](t: (A, B)) {
  import Numeric.Implicits._

  def + (p: (A, B)) = (p._1 + t._1, p._2 + t._2)
}

(2.0, 1) + (1.0, 2) == (3.0, 3)

Scalaz

import scalaz._, Scalaz._

scala> (1, 2.5) |+| (3, 4.4)
res0: (Int, Double) = (4,6.9)

There is an operator |+| for any class A with implicit Semigroup[A] in scope. For Int |+| is + by default (you could redefine it in your code).

There is an implicit Semigroup[(A, B)] for all tuples if there is implicit Semigroup for A and B.

See Scalaz cheat sheet.


This works with Cats as well, and similar to the scalaz answer:

> (1,2) |+| (1,3)
res3: (Int, Int) = (2, 5)

And likewise, it relies on Semigroup.

Tags:

Tuples

Scala