函数式编程中柯里化的价值是什么?
我知道柯里化的概念和如何使用,但我想知道它在实践中的价值是什么?
I know the concept and how to use of currying, but I wonder what is its value in practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如相关问题所涵盖的,实际使用柯里化函数?,有很多原因人们重视柯里化并利用它,包括:
map (+2)
更容易读比map (\x -> x + 2)
As the related question covers, Practical use of curried functions? , there are many reasons why people value currying and make use of it, including:
map (+2)
is easier to read thanmap (\x -> x + 2)
我发现的真正好处是:
错误更少 - 通过函数组合来编写代码往往会比命令式控制流产生更正确的代码。例如,如果您使用“map”而不是“for 循环”,则可以消除许多“相差一”索引错误的风险
更好的并发性 - 以及使用纯粹的、侧面创建的代码 -无效果函数自动是线程安全的。将其与不可变的持久数据结构结合起来,您就有了编写健壮并发代码的好方法。 Clojure 特别擅长于此 - 请参阅 http://www.infoq.com /presentations/Value-Identity-State-Rich-Hickey
更简洁且易于管理的代码 - 在我完全不科学的分析中,函数式代码似乎比命令式 OOP 代码短得多。随着程序规模的扩大,这种好处往往会更加明显。我认为有以下几个原因:
可测试性 - 当您主要使用纯函数编写代码时,编写健壮的测试非常容易。
当然,有一些缺点可以抵消这一点:
Real benefits I have found:
Less bugs - composing code by function composition tends to result in more correct code than imperative control flow. For example, if you use "map" rather than "for loops" you eliminate the risk of many "off by one" indexing errors
Better concurrency - and code you create with pure, side-effect free functions is automatically thread safe. Couple this with immutable persistent data structures and you have a great recipe for writing robust concurrent code. Clojure is particularly good for this - see http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey
More concise and manageable code - functional code seems in my completely unscientific analysis to be considerably shorter than imperative OOP code. The benefit tends to be more pronounced as programs get larger. I think there a several reasons for this:
Testability - when you write code primarily with pure functions, it's very easy to write robust tests.
There are some downsides to ofset this of course:
我想说这有点像一次且仅一次
在C/C++中我发现自己在写代码例如
而不是为每个 alpha 和 beta 编写一次 for 循环。这类似于过程代码中的柯里化。这里的优势是显而易见的。
柯里化是一个重要的理论概念,但从实践来看,这就是优势。
事实上,我记得曾经用 C 编写过一个测试套件,有点像这样:
这都是纯 C 语言,没有宏技巧等。函数式风格,有点像柯里化。这样做的好处是你可以一目了然地看到测试用例到底是什么。
data_set
类似——它将其参数绑定到另一个获取数据的函数:for_all
执行 thunk、检查谓词并进行清理。整齐的。I would say it's a bit like Once and Only Once
In C/C++ I find myself writing code such as
Instead of writing the for-loop once for each of alpha and beta. This is analagous to currying in procedural code. The advantage here is clear.
Currying is an important theoretical concept, but in practical terms, this is the advantage.
In fact, I remember writing a test suite in C once, it was a bit like this:
This was all in pure C, no macro trickery etc. Functional-style and kind of like currying. Here the advantage is you can see at a glance exactly what the test cases are.
data_set
is similar -- it binds its argument to another function which fetches the data:for_all
executes the thunk, checks the predicate, and cleans up. Tidy.