Skip to content

Instantly share code, notes, and snippets.

Created August 30, 2011 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/1180686 to your computer and use it in GitHub Desktop.
Save anonymous/1180686 to your computer and use it in GitHub Desktop.
user=> (map inc [1 2 3 4 5])
(2 3 4 5 6)
;; map can be used with multiple collections. Collections will be consumed
;; and passed to the mapping function in parallel:
user=> (map + [1 2 3] [4 5 6])
(5 7 9)
;; When map is passed more than one collection, the mapping function will
;; be applied until one of the collections runs out:
user=> (map + [1 2 3] (iterate inc 1))
(2 4 6)
;; map is often used in conjunction with the # reader macro:
user=> (map #(str "" % "") ["the" "quick" "brown" "fox"])
("the" "quick" "brown" "fox")
;; A useful idiom to pull "columns" out of a collection of collections:
user=> (apply map vector [[:a :b :c]
[:d :e :f]
[:g :h :i]])
([:a :d :g] [:b :e :h] [:c :f :i])
;; From http://clojure-examples.appspot.com/clojure.core/map
user=> (map #(vector (first %) (* 2 (second %)))
{:a 1 :b 2 :c 3})
([:a 2] [:b 4] [:c 6])
user=> (into {} *1)
{:a 2, :b 4, :c 6}
;; Use a hash-map as a function to translate values in a collection from the
;; given key to the associated value
user=> (map {2 "two" 3 "three"} [5 3 2])
(nil "three" "two")
;; then use (filter identity... to remove the nils
user=> (filter identity (map {2 "two" 3 "three"} [5 3 2]))
("three" "two")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment