scala 如何将函数应用于元组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1987820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to apply a function to a tuple?
提问by John Clements
This should be an easy one. How do I apply a function to a tuple in Scala? Viz:
这应该是一件容易的事。如何将函数应用于 Scala 中的元组?即:
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.
提前谢谢了。
回答by Randall Schulz
In Scala 2.8 and newer:
在 Scala 2.8 及更新版本中:
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 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>
回答by Jacek Laskowski
Following up on the other answer, one could write (tested with 2.11.4):
跟进另一个答案,可以写(用 2.11.4 测试):
scala> def f (i: Int, j: Int) = i + j
f: (i: Int, j: Int)Int
scala> val ff = f _
ff: (Int, Int) => Int = <function2>
scala> val p = (3,4)
p: (Int, Int) = (3,4)
scala> ff.tupled(p)
res0: Int = 7
See def tupled: ((T1, T2)) ? R:
参见def tupled: ((T1, T2)) ?[R :
Creates a tupled version of this function: instead of 2 arguments, it accepts a single scala.Tuple2argument.
创建此函数的元组版本:它接受单个scala.Tuple2参数而不是 2 个参数。
回答by jwvh
Scala 2.13
斯卡拉 2.13
def f (i : Int, j : Int) = i + j
import scala.util.chaining._
(3,4).pipe((f _).tupled) //res0: Int = 7
回答by Val K
scala> def f (i: Int, j: Int) = i + j
f: (i: Int, j: Int)Int
scala> val p = (3,4)
p: (Int, Int) = (3,4)
scala> val ft = (f _).tupled
ft: ((Int, Int)) => Int = <function1>
scala> ft apply(p)
res0: Int = 7

