mirror of
https://github.com/kanaka/mal.git
synced 2024-09-11 13:55:55 +03:00
Changes creating huge diffs, like file splits, have been delayed for readability . Also fix description of `and`.
48 lines
1.2 KiB
Plaintext
48 lines
1.2 KiB
Plaintext
;; FIXME lib/memoize.mal
|
|
;; Memoize any function.
|
|
|
|
;; Implement `memoize` using an atom (`mem`) which holds the memoized results
|
|
;; (hash-map from the arguments to the result). When the function is called,
|
|
;; the hash-map is checked to see if the result for the given argument was already
|
|
;; calculated and stored. If this is the case, it is returned immediately;
|
|
;; otherwise, it is calculated and stored in `mem`.
|
|
|
|
;; Adapted from http://clojure.org/atoms
|
|
|
|
(def! memoize
|
|
(fn* [f]
|
|
(let* [mem (atom {})]
|
|
(fn* [& args]
|
|
(let* [key (str args)]
|
|
(if (contains? @mem key)
|
|
(get @mem key)
|
|
(let* [ret (apply f args)]
|
|
(do
|
|
(swap! mem assoc key ret)
|
|
ret))))))))
|
|
|
|
nil
|
|
|
|
;; Benchmarks for memoize.mal
|
|
|
|
(load-file "../lib/heavy_computations.mal") ; fib
|
|
;; FIXME (load-file "../lib/memoize.mal")
|
|
(load-file "../lib/perf.mal") ; time
|
|
|
|
(def! N 32)
|
|
|
|
;; Benchmark naive 'fib'
|
|
|
|
(println "fib N=" N ": without memoization:")
|
|
(time (fib N))
|
|
;; "Elapsed time: 14402 msecs"
|
|
|
|
|
|
;; Benchmark memoized 'fib'
|
|
|
|
(def! fib (memoize fib))
|
|
|
|
(println "fib N=" N ": with memoization:")
|
|
(time (fib N))
|
|
;; "Elapsed time: 1 msecs"
|