Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decomposing tuples in function arguments

In python I can do this:

def f((a, b)):     return a + b  d = (1, 2) f(d) 

Here the passed in tuple is being decomposed while its being passed to f.

Right now in scala I am doing this:

def f(ab: (Int, Int)): Int = {     val (a, b) = ab     a + b }  val d = (1, 2) f(d) 

Is there something I can do here so that the decomposition happens while the arguments are passed in? Just curious.

like image 455
verma Avatar asked Jul 23 '12 15:07

verma


People also ask

Can you pass tuples as arguments for a function?

A tuple can also be passed as a single argument to the function. Individual tuples as arguments are just individual variables. A function call is not an assignment statement; it's a reference mapping.

Can I pass a tuple as argument in Python?

In Python, you can unpack list , tuple , dict (dictionary) and pass its elements to function as arguments by adding * to list or tuple and ** to dictionary when calling function.

How do you spread a tuple in Python?

To expand tuples into arguments with Python, we can use the * operator. to unpack the tuple (1, 2, 3) with * as the arguments of add . Therefore, a is 1, b is 2, and c is 3.

How many arguments does tuple take?

A tuple can be an argument, but only one - it's just a variable of type tuple . In short, functions are built in such a way that they take an arbitrary number of arguments.


2 Answers

You can create a function and match its input with pattern matching:

scala> val f: ((Int, Int)) => Int = { case (a,b) => a+b } f: ((Int, Int)) => Int  scala> f(1, 2) res0: Int = 3 

Or match the input of the method with the match keyword:

scala> def f(ab: (Int, Int)): Int = ab match { case (a,b) => a+b } f: (ab: (Int, Int))Int  scala> f(1, 2) res1: Int = 3 

Another way is to use a function with two arguments and to "tuple" it:

scala> val f: (Int, Int) => Int = _+_ f: (Int, Int) => Int = <function2>  scala> val g = f.tupled // or Function.tupled(f) g: ((Int, Int)) => Int = <function1>  scala> g(1, 2) res10: Int = 3  // or with a method scala> def f(a: Int, b: Int): Int = a+b f: (a: Int, b: Int)Int  scala> val g = (f _).tupled // or Function.tupled(f _) g: ((Int, Int)) => Int = <function1>  scala> g(1, 2) res11: Int = 3  // or inlined scala> val f: ((Int,Int)) => Int = Function.tupled(_+_) f: ((Int, Int)) => Int = <function1>  scala> f(1, 2) res12: Int = 3 
like image 56
kiritsuku Avatar answered Sep 27 '22 20:09

kiritsuku


Starting in Scala 3, with the improved tupled function feature:

// val tuple = (1, 2) // def f(a: Int, b: Int): Int = a + b f.tupled(tuple) // 3 

Play with it in Scastie

like image 44
Xavier Guihot Avatar answered Sep 27 '22 20:09

Xavier Guihot