foxlog
3/30/2018 - 2:22 AM

mapcat usage

mapcat usage

;;
;; clojrue.core
;;
(comment
  (defn mapcat
   "Returns the result of applying concat to the result of applying map
   to f and colls.  Thus function f should return a collection. Returns
   a transducer when no collections are provided"
   {:added "1.0"
    :static true}
   ([f] (comp (map f) cat))
   ([f & colls]
    (apply concat (apply map f colls)))))


;;
;; mapcat usage
;;
(require '[clojure.string :as cs])

;; Suppose you have a fn in a `map` that itself returns
;; multiple values.
(map #(cs/split % #"\d") ["aa1bb" "cc2dd" "ee3ff"])
;; (["aa" "bb"] ["cc" "dd"] ["ee" "ff"])

;; Now, if you want to concat them all together, you *could*
;; do this:
(apply concat (map #(cs/split % #"\d") ["aa1bb" "cc2dd" "ee3ff"]))
;;("aa" "bb" "cc" "dd" "ee" "ff")

;; But `mapcat` can save you a step:
(mapcat #(cs/split % #"\d") ["aa1bb" "cc2dd" "ee3ff"])
;;("aa" "bb" "cc" "dd" "ee" "ff")