下面fn2编译失败,
def fn(x: Int)(y: Int) = x + y
def fn2(f: ((Int)(Int)) => Int) = f
fn2(fn)(1)(2) // expected = 3
Run Code Online (Sandbox Code Playgroud)
如何定义fn2接受fn?
dk1*_*k14 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
Run Code Online (Sandbox Code Playgroud)
(Int)(Int) => Int是不正确的 - 你应该使用Int => Int => Int(比如在Haskell中).实际上,curried函数接受Int并返回Int => Int函数.
PS你也可以使用fn2(fn _)(1)(2),因为fn在前面的例子中只是简单的eta扩展形式,请参阅这些scala方法中下划线用法之间的差异.
| 归档时间: |
|
| 查看次数: |
182 次 |
| 最近记录: |