如何定义函数接受curried函数参数?

时间:2014-10-07 15:28:16

标签: scala

fn2以下未能编译,

def fn(x: Int)(y: Int) = x + y
def fn2(f: ((Int)(Int)) => Int) = f
fn2(fn)(1)(2) // expected = 3

如何定义fn2接受fn

1 个答案:

答案 0 :(得分:11)

应该如下:

scala> def fn2(f: Int => Int => Int) = f
fn2: (f: Int => (Int => Int))Int => (Int => Int)

scala> fn2(fn)(1)(2)
res5: Int = 3

(Int)(Int) => Int不正确 - 您应该使用Int => Int => Int(就像在Haskell中一样)。实际上,curried函数需要Int并返回Int => Int函数。

P.S。您也可以使用fn2(fn _)(1)(2),因为在前面的示例中传递fn只是一种简短的eta扩展形式,请参阅The differences between underscore usage in these scala's methods