Decomposing tuples in function arguments

后端 未结 3 1925
Happy的楠姐
Happy的楠姐 2020-12-29 02:02

In python I can do this:

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

d = (1, 2)
f(d)

Here the passed in tuple i

相关标签:
3条回答
  • 2020-12-29 02:34
    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
    
    0 讨论(0)
  • 2020-12-29 02:46

    With the upcoming Scala 3release schedule, and the improved tupled function feature, this will become possible:

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

    Play with it in Scastie

    0 讨论(0)
  • 2020-12-29 02:48

    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 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
    
    0 讨论(0)
提交回复
热议问题