Currying v.s. 的有用性(如在实际应用中)Scala 中的部分应用 [英] Usefulness (as in practical applications) of Currying v.s. Partial Application in Scala

查看:13
本文介绍了Currying v.s. 的有用性(如在实际应用中)Scala 中的部分应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解在 Scala 中对部分应用程序进行柯里化的优势.请考虑以下代码:

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)

那么,如果我可以这么容易地计算出部分应用函数,那么柯里化的优势是什么?

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)

如果最后一个参数不是函数或按名称参数,我不建议柯里化.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆