如何定义接受柯里化函数参数的函数? [英] How to define function accepting curried function parameter?
本文介绍了如何定义接受柯里化函数参数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
fn2
以下编译失败,
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
(就像在 Haskell 中一样).实际上,柯里化函数接受 Int
并返回 Int =>Int
函数.
(Int)(Int) => Int
is incorrect - you should use Int => Int => Int
(like in Haskell), instead. Actually, the curried function takes Int
and returns Int => Int
function.
附言您也可以使用 fn2(fn _)(1)(2)
,因为在前面的示例中传递 fn
只是 eta 扩展的一种简短形式,请参阅 这些scala方法中下划线用法的区别.
P.S. You could also use fn2(fn _)(1)(2)
, as passing fn
in previous example is just a short form of eta-expansion, see The differences between underscore usage in these scala's methods.
这篇关于如何定义接受柯里化函数参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文