Scala 中柯里化函数背后的基本原理是什么? [英] What's the rationale behind curried functions in Scala?

查看:56
本文介绍了Scala 中柯里化函数背后的基本原理是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Scala 的新手,我似乎有点困惑为什么 Scala 提供柯里化函数",例如:

I am just new to Scala and it seems a little bit confusing to me why Scala provides "curried functions" such as:

//curried function
def add(lhs: Int)(rhs: Int) = lhs + rhs
//so we can do partially binding like
val add1 = add(1)_

它令人困惑,因为 Scala 已经为普通函数提供了部分应用程序",例如,

Its confusing because Scala already provides 'partial application' to normal functions, e.g.,

//normal function
def add(lhs: Int, rhs: Int) = lhs + rhs
//also supports partially application
val add1 = add(1, _: Int) 

所以我的问题是:除了部分应用之外,在 Scala 中使用柯里化函数而不是普通函数还有其他意义吗?

So my question is: is there any other point of using a curried function rather than a normal function in Scala besides partial application?

EDT1:感谢您的回复.我想我从下面的所有答案中学到了新东西.

EDT1: Thanks for the replies. I think I have learned new stuff from all the answers below.

推荐答案

把理论动机放在一边(参见:对比维基百科中关于currying的部分函数应用,有实际意义.当最后一个参数是代码块时,语法更简单、更易读.

Putting the theoretical motivations aside (see: Contrast with partial function application in Wikipedia on currying), there is a practical implication. The syntax is much simpler and more readable when the last argument is a block of code.

比较以下方法:

def test1(name: String, callback: => Unit) {}
def test2(name: String)(callback: => Unit) {}

第二个方法调用看起来好多了,比较一下:

The second method invocation looks much nicer, compare:

test("abc", {
    //some code
})

test2("abc") {
    //some code
}

这篇关于Scala 中柯里化函数背后的基本原理是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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