如何定义接受curried函数参数的函数?
问题描述:
下面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
?
答
它应该是如下:
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。
请不要只说“编译失败”,还会给编译器提供错误信息。 – 2014-10-07 16:12:21