Created
April 22, 2010 05:47
-
-
Save hoeck/374865 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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