My comments were going to get too long winded, so...
- Nothing wrong with your code whatsoever.
- You might also see
(into {} (map (juxt identity f) coll))
- One common reason for doing this is to cache the results of a function over some inputs.
- There are other use-cases for what you have done, e.g. when a hash-map is specifically needed.
- If and only if #3 happens to be your use case, then
memoize does this for you.
If the function is f, and the resultant map is m then (f x) and (m x) have the same value in the domain. However, the values of (m x) have been precalculated, in other words, memoized.
Indeed memoize does exactly the same thing behind the scene, it just doesn't give direct access to the map. Here's a tiny modification to the source of memoize to see this.
(defn my-memoize
"Exactly the same as memoize but the cache memory atom must
be supplied as an argument."
[f mem]
(fn [& args]
(if-let [e (find @mem args)]
(val e)
(let [ret (apply f args)]
(swap! mem assoc args ret)
ret))))
Now, to demonstrate
(defn my-map-to-coll [f coll]
(let [m (atom {})
g (my-memoize f m)]
(doseq [x coll] (g x))
@m))
And, as in your example
(my-map-to-coll #(+ 2 %) [1 2 3])
;=> {(3) 5, (2) 4, (1) 3}
But note that the argument(s) are enclosed in a sequence as memoize handles multiple arity functions as well.
(into {} (map (juxt identity f) coll)). A similar function in core ismemoizefor the common use-case.memoize?f, and the resultant map ismthen(f x)and(m x)have the same value in thelstdomain. However, the values of(m x)have been precalculated, in other words, memoized.memoizebut I see nothing related to my question