【问题标题】:What is the significance of `flatmap` in SICP?SICP中`flatmap`的意义是什么?
【发布时间】:2020-09-04 20:51:24
【问题描述】:
(define (accumulate op initial sequence) 
  (if (null? sequence) 
   initial 
   (op (car sequence) 
     (accumulate op initial (cdr sequence))))) 
      
(define (flatmap proc seq) 
  (accumulate append nil (map proc seq)))

以上是SICP的一个代码sn-p,在Scheme中。为什么需要flatmap 过程? flatmapmap有什么区别?

【问题讨论】:

    标签: scheme sicp map-function flatmap


    【解决方案1】:

    (map proc seq)proc 应用于序列seq,为每个元素返回一个值。每个这样的值都可能是另一个序列。

    (accumulate append nil seq) 将使用appendseq 中元素的所有副本连接到一个新列表中。

    因此,flatmap 会将proc 应用于seq 的所有元素,并生成一个包含所有结果的新扁平 列表。从概念上讲,这也是其他语言(Java、Scala 等)中mapflatmap 的区别,因为map 为每个元素生成一个值,而flatmap 可能生成多个或不生成(谢谢克里斯)。

    例如,在 Clojure 中:

    (map #(clojure.string/split  % #"\s+") ["two birds" "with one stone"])
    ;; => (["two" "birds"] ["with" "one" "stone"])
    
    (mapcat #(clojure.string/split  % #"\s+") ["two birds" "with one stone"])
    ;; => ("two" "birds" "with" "one" "stone")
    

    【讨论】:

    • "...而 flatmap 可能会产生多个":为了原始发布者的利益,如果映射过程返回 '(),flatmap 也可能不会为元素产生任何值。您可以使用 flatmap 实现过滤器。
    猜你喜欢
    • 1970-01-01
    • 2022-08-23
    • 2010-11-13
    • 2011-08-19
    • 1970-01-01
    • 2020-01-23
    • 2013-03-31
    • 2014-03-30
    • 1970-01-01
    相关资源
    最近更新 更多