Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a function to a tuple?

Tags:

scala

This should be an easy one. How do I apply a function to a tuple in Scala? Viz:

 scala> def f (i : Int, j : Int) = i + j f: (Int,Int)Int  scala> val p = (3,4) p: (Int, Int) = (3,4)  scala> f p :6: error: missing arguments for method f in object $iw; follow this method with `_' if you want to treat it as a partially applied function        f p        ^  scala> f _ p :6: error: value p is not a member of (Int, Int) => Int        f _ p            ^  scala> (f _) p :6: error: value p is not a member of (Int, Int) => Int        (f _) p              ^  scala> f(p) :7: error: wrong number of arguments for method f: (Int,Int)Int        f(p)        ^  scala> grr! 

Many thanks in advance.

like image 624
John Clements Avatar asked Jan 01 '10 03:01

John Clements


People also ask

How do you add a tuple to a function?

Use Concatenation + to Append to a Tuple in Python Much like strings, tuple values can be altered or appended by simply concatenating a new value onto the existing one. It combines two different sets of tuples into one and doesn't actually change existing values, maintaining the immutability of the data type.

Is there a tuple function in Python?

The Python tuple() function is a built-in function in Python that can be used to create a tuple. A tuple is an ordered and immutable sequence type.

Can functions return a tuple?

Functions can return tuples as return values.

Is append a function in tuple?

Python tuple is an immutable object. Hence any operation that tries to modify it (like append) is not allowed. However, following workaround can be used.


1 Answers

In Scala 2.8 and newer:

scala> def f (i : Int, j : Int) = i + j f: (i: Int,j: Int)Int  // Note the underscore after the f scala> val ff = f _ ff: (Int, Int) => Int = <function2>  scala> val fft = ff.tupled fft: ((Int, Int)) => Int = <function1> 

In Scala 2.7:

scala> def f (i : Int, j : Int) = i + j f: (Int,Int)Int  // Note the underscore after the f scala> val ff = f _ ff: (Int, Int) => Int = <function>  scala> val fft = Function.tupled(ff) fft: ((Int, Int)) => Int = <function> 
like image 195
Randall Schulz Avatar answered Sep 23 '22 00:09

Randall Schulz