summaryrefslogtreecommitdiffstats
path: root/one
diff options
context:
space:
mode:
authorrsiddharth <s@ricketyspace.net>2016-08-22 03:03:16 +0000
committerrsiddharth <s@ricketyspace.net>2016-08-22 03:03:16 +0000
commit2662342bc85bbb6bf2af11c4559c94c9f5301284 (patch)
tree0fd8b107789a94a0ca89c4e003f7d6fad98f5b9d /one
parent3188380b871a4a18f5a12e3d52a8e0243954dcf2 (diff)
one/eleven.scm: add alt. version.
(make-cache, alt-recursive-fn): new functions.
Diffstat (limited to 'one')
-rw-r--r--one/eleven.scm31
1 files changed, 30 insertions, 1 deletions
diff --git a/one/eleven.scm b/one/eleven.scm
index d47fced..a95b7ab 100644
--- a/one/eleven.scm
+++ b/one/eleven.scm
@@ -3,10 +3,39 @@
;;;; <https://creativecommons.org/licenses/by-sa/4.0/>.
(define-module (one eleven)
- #:export (recursive-fn))
+ #:export (recursive-fn
+ make-cache
+ alt-recursive-fn))
(define (recursive-fn n)
(cond ((<= n 3) n)
(else (+ (* 1 (recursive-fn (- n 1)))
(* 2 (recursive-fn (- n 2)))
(* 3 (recursive-fn (- n 3)))))))
+
+;;;; alternative version. faster but ugly.
+
+(define (make-cache)
+ (let ((cache (make-hash-table)))
+ (define (get key)
+ (hash-get-handle cache key))
+ (define (set key value)
+ (hash-create-handle! cache key value)
+ ;; return value as a side effect.
+ value)
+ (lambda args
+ (apply (case (car args)
+ ((get) get)
+ ((set) set)
+ (else (error "Invalid method")))
+ (cdr args)))))
+
+(define (alt-recursive-fn cache n)
+ (let ((v (cache 'get n)))
+ (cond (v (cdr v))
+ ((<= n 3)
+ (cache 'set n n))
+ (else (cache 'set n
+ (+ (* 1 (alt-recursive-fn cache (- n 1)))
+ (* 2 (alt-recursive-fn cache (- n 2)))
+ (* 3 (alt-recursive-fn cache (- n 3)))))))))