Skip to content

Instantly share code, notes, and snippets.

@jbr
Created February 14, 2011 21:51
Show Gist options
  • Save jbr/826627 to your computer and use it in GitHub Desktop.
Save jbr/826627 to your computer and use it in GitHub Desktop.
;; ----------clojure beginner question------------
;; Let's say I have a vector of unique values or a
;; set and want to create a map with those as keys
;; and some transformation of them as values.
;; What's the idiomatic way to do this?
;; I'm using the following, but it seems there
;; should be a better way.
(defn build-map [initial-keys map-fn]
(loop [map {}
keys (seq initial-keys)]
(if keys
(recur (assoc map (first keys)
(map-fn (first keys)))
(next keys))
map)))
(build-map (range 0 5) (fn [n] (* 10 n)))
;=> {4 40, 3 30, 2 20, 1 10, 0 0}
;; Is there a way to do this with #clj.core/for
;; or something like that?
;; ------------- update ----------------
;; I found an answer:
(into {} (for [n (range 0 5)] [n (* 10 n)]))
;; Much nicer
@jbr
Copy link
Author

jbr commented Feb 14, 2011

Found the answer and updated the gist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment