2014-10-07 85 views
4

下面fn2无法编译,如何定义接受curried函数参数的函数?

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

如何定义fn2接受fn

+3

请不要只说“编译失败”,还会给编译器提供错误信息。 – 2014-10-07 16:12:21

回答

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),来代替。实际上,咖喱功能需要Int并返回Int => Int功能。

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