Skip to content

Instantly share code, notes, and snippets.

@Singletoned
Last active August 29, 2015 14:12
Show Gist options
  • Save Singletoned/1c001d6f64becd469782 to your computer and use it in GitHub Desktop.
Save Singletoned/1c001d6f64becd469782 to your computer and use it in GitHub Desktop.
(import [collections [OrderedDict]])
(defn lru-cache [&optional [limit 100]]
(defn inner [func]
(setv cache (OrderedDict))
(defn cached-fn [&rest args]
(let [[result nil]]
(try
(setv result (.pop cache args))
(catch [e KeyError]
(setv result (apply func args))
(if (> (len cache) limit)
(.popitem cache 0))))
(print "cache len" (len cache))
(setv (get cache args) result)
result))
cached-fn)
inner)
(with-decorator (lru-cache 100)
(defn foo [&rest args]
(print "in foo, " args)))
(foo 1 2)
(foo 1 2)
(foo 2 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment