In order to be lazy, the computer will have to do a linear scan of the input sequence each time a key is requested, at the very least if the key is beyond what has been scanned so far. A naive solution is just to scan the sequence every time, like 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 slightly less naive solution would be to use memoize
to cache the results of get-val
, though this would still scan the input sequence more than strictly necessary. A more aggressively caching solution would be to use an atom (as memoize
does internally) to cache each pair as it is seen, thereby only consuming more of the input sequence when a lookup requires something not yet seen.
Regardless, I would not recommend wrapping this up in a hash-map API, as that would imply efficient immutable "updates" that would likely not be needed and yet would be difficult to implement. I would also generally not recommend keywordizing the keys.