Shortcut to fetch tuple in function parafix in scala

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

list.map(tuple => {
  val (a, b) = tuple
  do_something(a,b)
})

// the previous can be shortened as follows
list.map{ case(a, b) =>
  do_something(a,b)
}

// similarly, how can I shorten this (and avoid declaring the 'tuple' variable)?
def f(tuple: (Int, Int)) {
  val (a, b) = tuple
  do_something(a,b)
}

// here there two ways, but still not very short,
// and I could avoid declaring the 'tuple' variable
def f(tuple: (Int, Int)) {
  tuple match {
    case (a, b) => do_something(a,b)
  }
}

def f(tuple: (Int, Int)): Unit = tuple match {
  case (a, b) => do_something(a,b)
}

      

+3


source to share


4 answers


Use tupled

scala> def doSomething = (a: Int, b: Int) => a + b
doSomething: (Int, Int) => Int

scala> doSomething.tupled((1, 2))
res0: Int = 3

scala> def f(tuple: (Int, Int)) = doSomething.tupled(tuple)
f: (tuple: (Int, Int))Int

scala> f((1,2))
res1: Int = 3

scala> f(1,2) // this is due to scala auto-tupling
res2: Int = 3

      



tupled

is defined for each FunctionN

with N >= 2

and returns a function that expects parameters, wrapped in a tuple.

+2


source


While this may seem like a trivial suggestion, the function f

can be simplified simply by using _1

it _2

in a tuple.

def f(tuple: (Int, Int)): Unit = 
    do_something(tuple._1, tuple._2)

      



Obviously, by doing this, you affect readability (some meta information about the value of the 1st and 2nd parameters of the tuple is removed), and if you want to use the elements of the tuple elsewhere in the method, f

you will need to retrieve them again.

Although for many applications this may be the simplest, shortest, and most intuitive alternative.

0


source


If I understand correctly, are you trying to pass a tuple to a method with two arguments?

def f(tuple: (Int,Int)) = do_something(tuple._1, tuple._2)

      

0


source


more readable, I mean providing variable names instead of using _1 an _2 in a tuple

In this case, it is recommended to use the case class instead of a tuple, especially since it only occupies one line:

case class IntPair(a: Int, b: Int)

def f(pair: IntPair) = do_something(pair.a, pair.b)

      

If you are getting (Int, Int)

from external code that cannot be changed (or you don’t want to change), you can add a conversion method from tuple to IntPair

.

Another option: {(a: Int, b: Int) => a + b}.tupled.apply(tuple)

. Unfortunately, it {case (a: Int, b: Int) => a + b}.apply(tuple)

doesn't work.

0


source







All Articles