2014-10-07 90 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

相關問題