hashmap - Clojure 2d list to hash-map -
i have infinite list that:
((1 1)(3 9)(5 17)...)
make hash map out of it:
{:1 1 :3 9 :5 17 ...)
basically 1st element of 'inner' list keyword, while second element value. not sure if not easier @ creation time, create list use:
(iterate (fn [[a b]] [(computation a) (computation b)]) [1 1])
computation of (b) requires (a) believe @ point (a) not keyword... whole point of 1 can access value (b) given (a).
any ideas appreciated...
--edit--
ok figured out:
(def my-map (into {} (map #(hash-map (keyword (str (first %))) (first (rest %))) my-list)))
the problem is: not seem lazy... goes forever though haven't consumed it. there way force lazy?
in order lazy, computer have linear scan of input sequence each time key requested, @ least if key beyond has been scanned far. naive solution scan sequence every time, this:
(defn get-val [coll k] (some (fn [[a b]] (when (= k a) b)) coll)) (get-val '((1 1)(3 9)(5 17)) 3) ;=> 9
a less naive solution use memoize
cache results of get-val
, though still scan input sequence more strictly necessary. more aggressively caching solution use atom (as memoize
internally) cache each pair seen, thereby consuming more of input sequence when lookup requires not yet seen.
regardless, not recommend wrapping in hash-map api, imply efficient immutable "updates" not needed , yet difficult implement. not recommend keywordizing keys.
Comments
Post a Comment