Skip to content

Commit b3e8b21

Browse files
committed
Merge pull request #445 from mpenet/feature/memo
add memoize
2 parents 0432ddd + b605646 commit b3e8b21

2 files changed

Lines changed: 21 additions & 0 deletions

File tree

pixie/stdlib.pxi

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff 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)))))

tests/pixie/tests/test-stdlib.pxi

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -728,3 +728,7 @@
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))))

0 commit comments

Comments
 (0)