Scala:分解函数参数中的元组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11615656/
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
Scala: Decomposing tuples in function arguments
提问by verma
In python I can do this:
在 python 中,我可以这样做:
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.
这里传入的元组在传递给 的同时被分解f。
Right now in scala I am doing this:
现在在 Scala 中,我正在这样做:
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.
我可以在这里做些什么,以便在传入参数时发生分解?只是好奇。
Thanks.
谢谢。
回答by kiritsuku
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 matchkeyword:
或者将方法的输入与match关键字匹配:
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
回答by jhegedus
object RandomExperiments extends App{
def takeTuple(t:(Int,Int))=print (s"$t ${t._1}\n")
takeTuple(1,3)
takeTuple((1,3))
takeTuple(((1,3)))
}
prints:
印刷:
(1,3) 1
(1,3) 1
(1,3) 1

