Skip to content

Instantly share code, notes, and snippets.

@hoeck
Created April 22, 2010 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoeck/374865 to your computer and use it in GitHub Desktop.
Save hoeck/374865 to your computer and use it in GitHub Desktop.
;; required: the latest master
;; memoized function (for one arg only, without implementing 'apply')
;; which implements IPersistentMap
(deftype MemoizedFn [mem-map f]
clojure.lang.IFn
(invoke [this a] (if-let [ret (find @mem-map a)]
(.val ret)
(let [ret (.invoke f a)]
(swap! mem-map assoc a ret)
ret)))
clojure.lang.IPersistentMap
(valAt [this k] (.invoke this k))
(containsKey [this k] (boolean (.invoke this k)))
(seq [this] (seq @mem-map))
(count [this] (count @mem-map))
(empty [this] {})
(equiv [this x] (.equiv @mem-map x))
;; how to implement those ?
(valAt [this k default])
(without [this k])
(assoc [this k v]))
(defn memoized-fn-map-hybrid [f]
(MemoizedFn. (atom {}) f))
(def mem (memoized-fn-map-hybrid #(* 2 %)))
(mem 2)
(mem 100)
(into {} mem)
(keys mem)
(vals mem)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment