功能语言中折叠/缩小的实际使用 [英] Practical use of fold/reduce in functional languages

查看:64
本文介绍了功能语言中折叠/缩小的实际使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Fold (又称 reduce )被认为是非常重要的高阶函数. Map 可以用 fold 表示(请参阅此处).但是,对我来说,这听起来比学术上的要多.一个典型的用法是获取数字的总和,乘积或最大值,但是这些函数通常接受任意数量的参数.那么为什么要在(+ 2 3 5)正常工作的情况下写(fold + 0'(2 3 5)).我的问题是,在什么情况下使用 fold 折叠最容易或最自然?

Fold (aka reduce) is considered a very important higher order function. Map can be expressed in terms of fold (see here). But it sounds more academical than practical to me. A typical use could be to get the sum, or product, or maximum of numbers, but these functions usually accept any number of arguments. So why write (fold + 0 '(2 3 5)) when (+ 2 3 5) works fine. My question is, in what situation is it easiest or most natural to use fold?

推荐答案

fold 的要点是它更加抽象.不是说您可以做以前做不到的事情,而是可以更轻松地做它们.

The point of fold is that it's more abstract. It's not that you can do things that you couldn't before, it's that you can do them more easily.

使用 fold ,您可以泛化在两个元素上定义的 any 函数以应用于任意数量的元素.这是一个胜利,因为与应用列表相比,通常更容易编写,测试,维护和修改应用两个参数的单个函数.而且,编写,测试,维护等总是容易得多.一个简单的功能,而不是两个具有类似但不十分相似的功能.

Using a fold, you can generalize any function that is defined on two elements to apply to an arbitrary number of elements. This is a win because it's usually much easier to write, test, maintain and modify a single function that applies two arguments than to a list. And it's always easier to write, test, maintain, etc. one simple function instead of two with similar-but-not-quite functionality.

由于 fold (因此, map filter 和朋友)具有明确的行为,因此通常更容易使用这些功能比使用显式递归更了解代码.

Since fold (and for that matter, map, filter, and friends) have well-defined behaviour, it's often much easier to understand code using these functions than explicit recursion.

基本上,一旦拥有一个版本,就可以免费"获得另一个版本.最终,您最终会减少工作量来获得相同的结果.

Basically, once you have the one version, you get the other "for free". Ultimately, you end up doing less work to get the same result.

这篇关于功能语言中折叠/缩小的实际使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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