Is there a easy way to add tuples which contain addable elements like Int, Doubles etc? For examples,
(1,2) + (1,3) = (2,5)
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.
+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 Int
s, 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)
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