From 2662342bc85bbb6bf2af11c4559c94c9f5301284 Mon Sep 17 00:00:00 2001 From: rsiddharth Date: Mon, 22 Aug 2016 03:03:16 +0000 Subject: one/eleven.scm: add alt. version. (make-cache, alt-recursive-fn): new functions. --- one/eleven.scm | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) 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 @@ ;;;; . (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))))))))) -- cgit v1.2.3