File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -2976,3 +2976,20 @@ ex: (vary-meta x assoc :foo 42)"
29762976 :added " 0.1" }
29772977 [x f & args]
29782978 (with - meta x (apply f (meta x) args)))
2979+
2980+ (defn memoize
2981+ {:doc " Returns a memoized version of function f. The first call will
2982+ realize the return value and subsequent calls get the same value
2983+ from its cache."
2984+ :signatures [[f]]
2985+ :added " 0.1" }
2986+ [f]
2987+ (let [cache (atom {})]
2988+ (fn [& args]
2989+ (let [argsv (vec args)
2990+ val (get @cache argsv ::not - found)]
2991+ (if (= val ::not - found)
2992+ (let [ret (apply f args)]
2993+ (swap! cache assoc argsv ret)
2994+ ret)
2995+ val)))))
Original file line number Diff line number Diff line change 728728
729729(t/ deftest test- vary- meta
730730 (t/ assert = 42 (- > {} (vary- meta assoc :foo 42 ) meta :foo)))
731+
732+ (t/ deftest test- memoize
733+ (let [f (memoize rand)]
734+ (t/ assert = (f) (f))))
You can’t perform that action at this time.
0 commit comments