分解函数参数中的元组 [英] Decomposing tuples in function arguments

查看:89
本文介绍了分解函数参数中的元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,我可以这样做:

In python I can do this:

def f((a, b)):
    return a + b

d = (1, 2)
f(d)

这里,传入的元组在传递给f时正在分解.

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.

推荐答案

您可以创建一个函数并将其输入与模式匹配相匹配:

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

或将方法的输入与match关键字进行匹配:

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

这篇关于分解函数参数中的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆