Currying v.s.的实用性(在实际应用中)在Scala中的部分应用 [英] Usefulness (as in practical applications) of Currying v.s. Partial Application in Scala
问题描述
我试图了解在Scala中使用currying优于部分应用程序的优势.请考虑以下代码:
I'm trying to understand the advantages of currying over partial applications in Scala. Please consider the following code:
def sum(f: Int => Int) = (a: Int, b: Int) => f(a) + f(b)
def sum2(f: Int => Int, a: Int, b: Int): Int = f(a) + f(b)
def sum3(f: Int => Int)(a: Int, b: Int): Int = f(a) + f(b)
val ho = sum({identity})
val partial = sum2({ identity }, _, _)
val currying = sum3({ identity })
val a = currying(2, 2)
val b = partial(2, 2)
val c = ho(2, 2)
那么,如果我能这么容易地计算出部分应用函数,那么使用currying有什么好处?
So, if I can calculate partially applied function that easy, what are the advantages of currying?
推荐答案
如果第二个参数部分是函数或按名称参数,则通常使用咖喱.这有两个优点.首先,函数参数可以看起来像括在括号中的代码块.例如
Currying is mostly used if the second parameter section is a function or a by name parameter. This has two advantages. First, the function argument can then look like a code block enclosed in braces. E.g.
using(new File(name)) { f =>
...
}
这比未使用的替代方法读起来更好:
This reads better than the uncurried alternative:
using(new File(name), f => {
...
})
第二,更重要的是,类型推断通常可以找出函数的参数类型,因此不必在调用站点中给出.
例如,如果我在这样的列表上定义max
函数:
Second, and more importantly, type inference can usually figure out the function's parameter type, so it does not have to be given at the call site.
For instance, if I define a max
function over lists like this:
def max[T](xs: List[T])(compare: (T, T) => Boolean)
我可以这样称呼它:
max(List(1, -3, 43, 0)) ((x, y) => x < y)
或更短:
max(List(1, -3, 43, 0)) (_ < _)
如果我将max
定义为一个非咖喱函数,那将无法正常工作,我必须这样称呼它:
If I defined max
as an uncurried function, this would not work, I'd have to call it like this:
max(List(1, -3, 43, 0), (x: Int, y: Int) => x < y)
如果最后一个参数不是函数或名称参数,我不建议使用curring. Scala的_
注释几乎是轻量级的,更灵活的且更清晰的IMO.
If the last parameter is not a function or by-name parameter, I would not advise currying. Scala's _
notatation is amost as lightweight, more flexible, and IMO clearer.
这篇关于Currying v.s.的实用性(在实际应用中)在Scala中的部分应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!