Skip to content

Instantly share code, notes, and snippets.

@BadUncleX
Last active April 11, 2018 02:34
Show Gist options
  • Save BadUncleX/e34bb4c5bf7e60b506f53c897ba1f4ca to your computer and use it in GitHub Desktop.
Save BadUncleX/e34bb4c5bf7e60b506f53c897ba1f4ca to your computer and use it in GitHub Desktop.
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")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment