You're viewing version 1.2.0 of map. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16
  • (map f coll)
  • (map f c1 c2)
  • (map f c1 c2 c3)
  • (map f c1 c2 c3 & colls)
Returns a lazy sequence consisting of the result of applying f to the
set of first items of each coll, followed by applying f to the set
of second items in each coll, until any one of the colls is
exhausted. Any remaining items in other colls are ignored. Function
f should accept number-of-colls arguments.

6 Examples top

  • 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 "Hello " % "!" ) ["Ford" "Arthur" "Tricia"])
    ("Hello Ford!" "Hello Arthur!" "Hello Tricia!")
    
    ;; A useful idiom to pull "columns" out of a collection of collections. 
    ;; Note, it is equivalent to:
    ;; user=> (map vector [:a :b :c] [:d :e :f] [:g :h :i])
    
    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")
  • ;; mapping over a hash-map applies (into) first. 
    ;; need to use functions that deal with arrays (fn [[key val]] ...)
    (map pprint {:key :val :key1 :val1})
    ([:key :val]
    [:key1 :val1]
    nil nil)
    
    ;;above, the pprint output appears to be part of the return value but it's not:
    (hash-set (map pprint {:key :val :key1 :val1}))
    [:key :val]
    [:key1 :val1]
    #{(nil nil)}
    
    (map second {:key :val :key1 :val1})
    (:val :val1)
  • (map fn [a 4 x]
            [b 5 y]
            [c 6])    
    ;        ^ ^
    ; applies fn to a b c as (fn a b c)
    ; applies fn to 4 5 6 as (fn 4 5 6)
    ; ignores (x y)
    ; returns a list of results
    ; equivalent to (list (fn a b c) (fn 4 5 6))
    
    ;example
    (map list [1 2 3]
             '(a b c)
             '(4 5))
    
    user=> (map list  [1 2 3] '(a b c) '(4 5))
    ((1 a 4) (2 b 5))
    ;same as
    user=> (list (list 1 'a 4) (list 2 'b 5))
    ((1 a 4) (2 b 5))
  • ; map passed two collection arguments. From 4Clojure Problem #157
    
    (def d1 [:a :b :c])
    (#(map list % (range)) d1)
    ((:a 0) (:b 1) (:c 2))
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:2079 top

(defn map
  "Returns a lazy sequence consisting of the result of applying f to the
  set of first items of each coll, followed by applying f to the set
  of second items in each coll, until any one of the colls is
  exhausted.  Any remaining items in other colls are ignored. Function
  f should accept number-of-colls arguments."
  {:added "1.0"}
  ([f coll]
   (lazy-seq
    (when-let [s (seq coll)]
      (if (chunked-seq? s)
        (let [c (chunk-first s)
              size (int (count c))
              b (chunk-buffer size)]
          (dotimes [i size]
              (chunk-append b (f (.nth c i))))
          (chunk-cons (chunk b) (map f (chunk-rest s))))
        (cons (f (first s)) (map f (rest s)))))))
  ([f c1 c2]
   (lazy-seq
    (let [s1 (seq c1) s2 (seq c2)]
      (when (and s1 s2)
        (cons (f (first s1) (first s2))
              (map f (rest s1) (rest s2)))))))
  ([f c1 c2 c3]
   (lazy-seq
    (let [s1 (seq c1) s2 (seq c2) s3 (seq c3)]
      (when (and  s1 s2 s3)
        (cons (f (first s1) (first s2) (first s3))
              (map f (rest s1) (rest s2) (rest s3)))))))
  ([f c1 c2 c3 & colls]
   (let [step (fn step [cs]
                 (lazy-seq
                  (let [ss (map seq cs)]
                    (when (every? identity ss)
                      (cons (map first ss) (step (map rest ss)))))))]
     (map #(apply f %) (step (conj colls c3 c2 c1))))))
Used in 228 other vars (expand)
find-protocol-impl letfn keys zipmap lazy-cat import vals assoc doto mapcat destructure pvalues ns proxy-name drop-last replace dissoc! interleave get declare ancestors definterface find dissoc dir-fn rename-keys project rename do-template testing-vars-str test-name walk keywordize-keys stringify-keys apply-macro classpath-jarfiles classpath all-predicates display-rule get-all-relations non-base-rules reverse-map preduce build-partial-tuple indexed deferror find-ns-decls-in-jarfile find-namespaces-in-dir find-namespaces-in-jarfile find-namespaces-on-classpath find-ns-decls-in-dir generate-documentation generate-all-namespaces-action-script defadt add-loops remove-loops import-static filenames-in-jar op-param-types tabular-data->map operation-names composite-data->map map->attribute-infos attribute-names mbean fibs macrolet with-symbol-macros symbol-macrolet lazy-get safe-get safe-get-in make-arg-checker ns-vars m-map defmonadfn toks add-core-ns binomial lcg reductions rotations indexed reductions rotations create-table map-str map-str do-template testing-vars-str with-ns children children-auto assoc-param sample-mvn sample-dirichlet pdf-normal cdf-normal add-function* conj-cols cumulative-mean function-plot* sliders group-on sliders* defop to-vect combine-with make-matrix transform-with matrix-map to-matrix $map read-dataset read-xls hessian gradient cdf-t pdf-f cdf-exp pdf-neg-binomial mahalanobis-distance cdf-gamma cdf-beta lee-distance sample square-devs-from-mean pdf-poisson pdf-exp n-grams pdf-gamma cdf-poisson cdf-uniform pdf-binomial cdf-binomial cdf-chisq pdf-chisq pdf-uniform cdf-f hamming-distance pdf-t minkowski-distance sum-variance-test pdf-beta cdf-neg-binomial chebyshev-distance deriv-fn* define-all-ant-tasks task-names compile read-git-origin tests testing-fn for-these test-namespaces make-arg-checker for-these tests test-namespaces ns-vars story-lines context-lines indent-lines testing-fn report-tally tally test-results local-bindings java-props->sh-args local-bindings snippet* text flatmap defsnippets select-nodes* texts select-fragments* let-select parse swank who-specializes locals-for-emacs exception-stacktrace list-threads one-of? list-all-package-names local-bindings format-restarts-for-emacs largest-common-prefix apropos-list-for-emacs who-calls deep-replace potential-static potential-dot top-level-classes potential-completions nested-classes compound-prefix-match? fuzzy-completions inspector-content ns-refers-by-ns label-value-line* all-vars-who-call swank-packages swank-version fake run-list i-want partial-namespace-matcher combine-matchers new-sandbox-compiler namespace-matcher class-matcher default-obj-tester function-matcher fn-seq secure-tester combine-testers button-group auto-setters icon-setters kw-to-setter combo-box jlist combinations expect make-arg-checker permutations

Comments top

No comments for map. Log in to add a comment.