Skip to content

Commit b605646

Browse files
committed
add memoize
1 parent 4c9bf17 commit b605646

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
@@ -2974,3 +2974,20 @@ ex: (vary-meta x assoc :foo 42)"
29742974
:added "0.1"}
29752975
[x f & args]
29762976
(with-meta x (apply f (meta x) args)))
2977+
2978+
(defn memoize
2979+
{:doc "Returns a memoized version of function f. The first call will
2980+
realize the return value and subsequent calls get the same value
2981+
from its cache."
2982+
:signatures [[f]]
2983+
:added "0.1"}
2984+
[f]
2985+
(let [cache (atom {})]
2986+
(fn [& args]
2987+
(let [argsv (vec args)
2988+
val (get @cache argsv ::not-found)]
2989+
(if (= val ::not-found)
2990+
(let [ret (apply f args)]
2991+
(swap! cache assoc argsv ret)
2992+
ret)
2993+
val)))))

tests/pixie/tests/test-stdlib.pxi

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -726,3 +726,7 @@
726726

727727
(t/deftest test-vary-meta
728728
(t/assert= 42 (-> {} (vary-meta assoc :foo 42) meta :foo)))
729+
730+
(t/deftest test-memoize
731+
(let [f (memoize rand)]
732+
(t/assert= (f) (f))))

0 commit comments

Comments
 (0)