【问题标题】:What is the different between filter and filter-map?过滤器和过滤器映射有什么区别?
【发布时间】:2019-05-01 18:18:02
【问题描述】:

我想了解count 做了什么。

我已经阅读了文档,上面写着:

返回 (length (filter-map proc lst ...)),但不构建 中间列表。

然后,我阅读了filter-map 文档,上面写着:

返回 (filter (lambda (x) x) (map proc lst ...)),但没有 构建中间列表。

然后,我已经阅读了filter 的文档,我已经明白了。

但是,我不明白filter-map。特别是(lambda (x) x) in (filter (lambda (x) x) (map proc lst ...))

filterfilter-map 有什么区别?

顺便说一句,filterfilter-map 的例子也是如此,这让他们更难理解。

【问题讨论】:

  • (filter-map (lambda (x) (if (even? x) (list x x) #f)) '(1 2 3 4 5)) ==> '((2 2) (4 4)).

标签: racket


【解决方案1】:

我想说这里的关键见解是,在filter 的上下文中,您应该将(lambda (x) x) 阅读为not-false?。所以,filter-map 的文档可以写成这样:

返回(filter not-false? (map proc lst ...)),但不构建中间列表,其中not-false?可以定义为(lambda (x) x)

【讨论】:

  • 跟进:现已提议更改文档以澄清这一点。感谢@VansFannel 的提示!
  • 不客气。我很高兴成为社区的一员。
【解决方案2】:

重点是,如果你很了解filtermap,那么你可以这样解释filter-map。如果您不知道filtermap 是做什么的,它不会帮助您理解它。当您需要学习新事物时,您通常需要使用先前的经验。例如。我可以通过说 3 * 43 + 3 + 3 + 3 相同来解释乘法,但如果您不知道 + 是什么,这将无济于事。

filterfilter-map有什么区别

(filter odd? '(1 2 3 4 5))     ; ==> (1 3 5)
(filter-map odd? '(1 2 3 4 5)) ; ==> (#t #t #t))

当谓词变为真时,第一个从列表中收集原始值。在这种情况下,(odd? 1) 为真,因此1 是结果中的一个元素。

filter-map 不会过滤 odd? 它就像您将 odd? 传递给 map 一样。在那里你会得到一个包含结果的新列表。

(map odd? '(1 2 3 4 5))                   ; ==> (#t #f #t #f #t #f)

然后它会删除假值,这样你就只剩下真值了:

(filter identity (map odd? '(1 2 3 4 5))) ; ==> (#t #t #t)

现在。重要的是要理解,在 Scheme 中,除了 #f 之外的每个值都是 true。 (lambda (x) x) 是恒等函数,与#lang racket 中的identity 相同。它返回自己的参数。

(filter identity '(1 #f 2 #f 3)) ; ==> (1 2 3)

countfilter-map 的工作方式相同,只是它只返回您将获得多少元素。因此:

(count odd? '(1 2 3 4 5)) ; ==> 3

现在它提到它与以下内容相同:

(length (filter identity (map odd? '(1 2 3 4 5)))

因为使用mapfilterlength 的代码创建了2 个列表。因此,虽然 count 做同样的事情,但它没有使用 mapfilter。现在看来这是一个原始的,但你可以这样做:

(define (count fn lst)
  (let loop ((lst lst) (cnt 0))
    (cond ((null? lst) cnt)
          ((fn (car lst)) (loop (cdr lst) (add1 cnt)))
          (else (loop (cdr lst) cnt))))

【讨论】:

    猜你喜欢
    • 2019-02-11
    • 2015-04-18
    • 1970-01-01
    • 2016-10-27
    • 2015-11-15
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    相关资源
    最近更新 更多