mapcat

此頁面描述集合管線模式中的操作。如需更多背景資訊,請閱讀

flat-map

對集合映射函數並將結果扁平化一層

通常會想要對輸入清單映射函數,該函數會在清單中傳回多個值,但您不希望輸出像輸入一樣嵌套。

ruby…
["two birds", "three green peas"].
  flat_map {|s| s.split}
# => ["two", "birds", "three", "green", "peas"]
clojure…
(mapcat #(clojure.string/split  % #"\s+") 
        ["two birds" "three green peas"])
;; => ("two" "birds" "three" "green" "peas")

邏輯上,這與 map 後接單層 flatten 相同。

ruby…
["two birds", "three green peas"].
  map {|s| s.split}.
  flatten (1)
# => ["two", "birds", "three", "green", "peas"]

但它非常常用,以至於許多平台都提供 flat-map 操作。

您也可以將其視為取得 map 的所有結果並將結果串接在一起,因此 clojure 名稱為「mapcat」。

clojure…
(apply concat (map #(clojure.string/split  % #"\s+") 
                   ["two birds" "three green peas"]))
;; => ("two" "birds" "three" "green" "peas")