clojure-style-guide icon indicating copy to clipboard operation
clojure-style-guide copied to clipboard

(into {} (for ... )) — curly or square brackets to return map entries

Open martinklepsch opened this issue 10 years ago • 2 comments
trafficstars

E.g.

(into {}
      (for [n [:a :b :c]]
        [n (name n)]))
;; vs.
(into {}
      (for [n [:a :b :c]]
        {n (name n)}))

:smile:

martinklepsch avatar Jun 18 '15 22:06 martinklepsch

nrepl> (time (do ;; vs.
               (into {}
                     (for [n (range 10000000)]
                       [n n]))
               nil))
"Elapsed time: 14067.538884 msecs"
nil
nrepl> (time (do ;; vs.
               (into {}
                     (for [n (range 10000000)]
                       {n n}))
               nil))
"Elapsed time: 17612.829969 msecs"
nil

For performance, the [k v] vector pair should be preferred although the difference isn't really significant except for large inputs.

Furthermore from a types sense (into {} (e -> [[k v]] -> {[k v]}) makes somewhat sense than the map merge form of into.

arrdem avatar Jun 18 '15 22:06 arrdem

Because seq on a map produces a list of vectors, I find it more natural to use vectors for building a map also.

(seq {:a 1 :b 2})
=> ([:a 1] [:b 2])

For your special use case, there is also for-map from Prismatic plumbing.

alexanderkiel avatar Jun 19 '15 07:06 alexanderkiel