DrRacket/方案中的地图,过滤器,文件夹 [英] Map, Filter, Foldr in DrRacket/Scheme

查看:106
本文介绍了DrRacket/方案中的地图,过滤器,文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编程语言:Scheme/DrRacket

Programming language: Scheme/DrRacket

我们目前正在我的comp sci类中浏览mapfilterfoldr.我知道可以使用这三个函数来创建抽象函数,但是老实说,我对这三个函数以及何时使用它们之间的区别感到有些困惑.

We're currently going over map, filter, and foldr in my comp sci class. I understand that all three can be used to create abstract functions, but I am honestly a little confused about the difference between the three and when I'd use each one.

每个人都在乎解释它们的用途以及它们之间的不同之处吗?不幸的是我的书不是很清楚.

Anyone care to explain what each is used for and how they are different? Unfortunately my book is not very clear.

推荐答案

基本思想是,所有这三种都是将某些功能应用于列表的所有元素的方式.

The basic idea is that all three are ways of applying some function to all the elements of a list.

地图也许是最简单的-您只需将函数应用于列表的每个元素.这基本上与其他语言中的for-each循环相同:

Map is perhaps the simplest--you just apply the function to each element of the list. This is basically the same as a for-each loop in other languages:

 (map (lambda (x) (+ x 1)) '(1 2 3))
   => (2 3 4)

基本上,地图是这样的:(map f '(1 2 3))(list (f 1) (f 2) (f 3))相同.

Basically, map is like this: (map f '(1 2 3)) is the same as (list (f 1) (f 2) (f 3)).

过滤器也很简单:该函数就像一个仲裁器,决定是否保留每个数字.想象一下一个非常挑剔的食者正在浏览菜单并抱怨他不会吃的东西;)

Filter is also simple: the function acts like an arbiter, deciding whether to keep each number. Imagine a really picky eater going through a menu and whining about the things he won't eat ;)

 (filter (lambda (x) (equal? x 1)) '(1 2 3))
   => (1)

我认为,折叠是最难理解的.一个更直观的名称是累计".这样的想法是,您可以在进行过程中合并"列表.日常使用中有些功能实际上是可折叠的-sum是一个很好的例子.

Fold is the hardest to understand, I think. A more intuitive name would be "accumulate". The idea is that you're "combining" the list as you go along. There are some functions in ever day use that are actually folds--sum is a perfect example.

 (foldr + 0 '(1 2 3)) 
   => 6

您可以将折叠视为将函数放在列表中的每个元素之间:(foldr + 0 '(1 2 3))1 + 2 + 3 + 0相同.

You can think of the fold as taking the function and putting it between each element in the list: (foldr + 0 '(1 2 3)) is the same as 1 + 2 + 3 + 0.

折叠是特殊的,因为与其他两个折叠不同,它通常返回标量值-这是列表的元素,而不是列表本身. (并非总是如此,但无论如何现在还是这样想.)

Fold is special because, unlike the other two, it usually returns a scalar value--something that was the element of the list rather than the list itself. (This isn't always true, but think of it this way for now anyway.)

请注意,我可能并没有使代码的每个细节都完美无缺-我只使用了一个不同的,较旧的Scheme实现,因此我可能错过了一些Racket细节.

Note that I may not have gotten every detail of the code perfect--I've only ever used a different, older implementation of Scheme so I might have missed some Racket details.

这篇关于DrRacket/方案中的地图,过滤器,文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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