Estaban Quito
Estaban Quito

Reputation: 31

What does Clojure's zip-map do?

I am new at Clojure and I needed help with this function. If you could please tell me what this function does and how it works I would be really thankfull.

(defn zip-map
  [k v]
    (into{} (map vec (partition 2 (interleave k v)))))

Upvotes: 0

Views: 940

Answers (2)

Thumbnail
Thumbnail

Reputation: 13483

The function is more complicated hence harder to understand than it need be. It could be written thus:

(defn zip-map [ks vs]
  (into {} (map vector ks vs)))

when

(zip-map [:a :b :c] [1 2 3])
;{:a 1, :b 2, :c 3}

as before.

The function imitates the standard zipmap, which you can find explained, complete with source code, in the official docs or ClojureDocs, which also gives examples. Both these sites help you to pick your way through the Clojure vocabulary.

As is often the case, the standard function is faster though more complex than the simple one-liner above.

Upvotes: 2

ponzao
ponzao

Reputation: 20944

Example of usage:

(zip-map [:a :b :c] [1 2 3]) ;=> {:a 1, :b 2, :c 3}    

And from the inside out:

(interleave [:a :b :c] [1 2 3]) ;=> (:a 1 :b 2 :c 3)
(partition 2 '(:a 1 :b 2 :c 3)) ;=> ((:a 1) (:b 2) (:c 3))
(map vec '((:a 1) (:b 2) (:c 3))) ;=> ([:a 1] [:b 2] [:c 3])
(into {} '([:a 1] [:b 2] [:c 3])) ;=> {:a 1, :b 2, :c 3}

Upvotes: 8

Related Questions