Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add two tuples containing simple elements in Scala

Tags:

tuples

scala

Is there a easy way to add tuples which contain addable elements like Int, Doubles etc? For examples,

(1,2) + (1,3) = (2,5)
like image 369
Arun Avatar asked Oct 26 '13 12:10

Arun


2 Answers

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.

like image 129
senia Avatar answered Nov 05 '22 20:11

senia


+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)
like image 23
Konrad 'ktoso' Malawski Avatar answered Nov 05 '22 22:11

Konrad 'ktoso' Malawski