如何从Scala中的a=>b=>c获得(a,b)=>c?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (59)

如果我有:

val f : A => B => C

这是以下简称:

val f : Function1[A, Function1[B, C]]

我如何得到一个函数g签名:

val g : (A, B) => C = error("todo")

(即)

val g : Function2[A, B, C] //or possibly
val g : Function1[(A, B), C]

提问于
用户回答回答于
scala> val f : Int => Int => Int = a => b => a + b
f: (Int) => (Int) => Int = <function1>

scala> Function.uncurried(f)
res0: (Int, Int) => Int = <function2>
用户回答回答于

为了完整答案

val f : Int => Int => Int = a => b => a + b
val g: (Int, Int) => Int = Function.uncurried(f)
val h: ((Int, Int)) => Int = Function.tupled(g)

这两个操作的逆函数也都在函数对象上提供,因此如果愿意,可以向后写上面的内容。

val h: ((Int, Int)) => Int =  x =>(x._1 + x._2)
val g: (Int, Int) => Int = Function.untupled(h)
val f : Int => Int => Int = g.curried  //Function.curried(g) would also work, but is deprecated. Wierd

扫码关注云+社区