Home > database >  How to multiply a tuple or a list of integers with a factor in Scala
How to multiply a tuple or a list of integers with a factor in Scala

Time:04-05

In Scala 2 I have a tuple like this:

val direction = (2,3) 

This value direction I want to multiply with a Int factor f in order to get a new tuple

(2 * f, 3 * f)

So if f=4 I looking for the result (8,12).

I tried the obvious candidate *:

(2,3) * f

but * doesn't seem to be designed for these types.

CodePudding user response:

How about this?

// FUNCTION
object TupleProduct extends App {

  implicit class TupleProduct(tuple2: (Int, Int)) {
    def * : Int => (Int, Int) = (f: Int) => {
      (tuple2._1 * f, tuple2._2 * f)
    }
  }

  val direction = (2, 3)

  print(direction * 4)
}

// METHOD
object TupleProduct extends App {

  implicit class TupleProduct(tuple2: (Int, Int)) {
    def *(f: Int):(Int, Int) = {
      (tuple2._1 * f, tuple2._2 * f)
    }
  }

  val direction = (2, 3)

  print(direction * 4)
}

CodePudding user response:

Also TupleN has productIterator:

(1,2,3,4,5)
  .productIterator
  .map { case n: Int => n * 2 }
  .toList

This doesn't return another tuple but gives you easy iteration through all elements without a

productIterator returns Iterator[Any] so you gotta use pattern matching.

  • Related