sicp

sicp sandbox.
git clone git://git.ricketyspace.net/sicp.git
Log | Files | Refs

commit 2662342bc85bbb6bf2af11c4559c94c9f5301284
parent 3188380b871a4a18f5a12e3d52a8e0243954dcf2
Author: rsiddharth <s@ricketyspace.net>
Date:   Mon, 22 Aug 2016 03:03:16 +0000

one/eleven.scm: add alt. version.

(make-cache, alt-recursive-fn): new functions.

Diffstat:
one/eleven.scm | 31++++++++++++++++++++++++++++++-
1 file changed, 30 insertions(+), 1 deletion(-)

diff --git 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)))))))))