This page describes an operation in the collection pipeline pattern. For more context read:
- Collection Pipeline Article: An article explaining the collection pipeline pattern
- Operation Catalog: The list of selected operations that I have these pages for.
flat-map
Map a function over a collection and flatten the result by one-level
It's common to want to map a function on an input list that returns multiple values in a list, but you don't want the output nested in the same way as the input was.
["two birds", "three green peas"]. flat_map {|s| s.split} # => ["two", "birds", "three", "green", "peas"]
(mapcat #(clojure.string/split % #"\s+") ["two birds" "three green peas"]) ;; => ("two" "birds" "three" "green" "peas")
Logically this is the same as a map followed by a single-level flatten.
ruby…["two birds", "three green peas"]. map {|s| s.split}. flatten (1) # => ["two", "birds", "three", "green", "peas"]
But it's so commonly needed that many platforms provide a flat-map operation.
You can also consider it to be the same as taking all the results of the map and concatenating the results together - hence the clojure name of “mapcat”.
clojure…(apply concat (map #(clojure.string/split % #"\s+") ["two birds" "three green peas"])) ;; => ("two" "birds" "three" "green" "peas")