【问题标题】:Decomposing tuples in function arguments分解函数参数中的元组
【发布时间】:2012-07-21 20:57:33
【问题描述】:

在 python 中我可以这样做:

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

d = (1, 2)
f(d)

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

现在在 scala 中我正在这样做:

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

val d = (1, 2)
f(d)

我可以在这里做些什么,以便在传入参数时进行分解?只是好奇。

【问题讨论】:

标签: scala function tuples


【解决方案1】:

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

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

scala> f(1, 2)
res0: Int = 3

或者用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

另一种方法是使用带有两个参数的函数并“元组”它:

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

【讨论】:

    【解决方案2】:

    Scala 3 开始,改进了tupled function 功能:

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

    Scastie玩它

    【讨论】:

      【解决方案3】:
      object RandomExperiments extends App{
        def takeTuple(t:(Int,Int))=print (s"$t ${t._1}\n")
        takeTuple(1,3)
        takeTuple((1,3))
        takeTuple(((1,3)))
      
      }
      

      打印:

      (1,3) 1
      (1,3) 1
      (1,3) 1
      

      【讨论】:

      • 这与 Brian Agnews 的回答基本相同。但也许这是愚人节的玩笑?
      • 第一个有效,因为可以在 scala 中使用不带括号的语法。它不是用两个参数调用 takeTuple,而是用一个元组参数调用 takeTuple,而不用括号包裹参数(实际上在 #2 中完成)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-08
      • 2019-09-01
      相关资源
      最近更新 更多