Last active
June 24, 2025 18:20
-
-
Save gambiteer/40d1c2d5a1995df401c873ad9d333e48 to your computer and use it in GitHub Desktop.
Caching exponentials of computable reals
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(define basic-expt | |
(let ((global-exponent-table | |
(make-table weak-keys: #t weak-values: #t test: eq?))) | |
;; x is a computable real | |
;; n is an exact integer | |
(define (global-return x closure) | |
(table-set! global-exponent-table x closure) | |
closure) | |
(lambda (x) | |
(cond | |
;; if you find x in the table, use it | |
((table-ref global-exponent-table x #f)) | |
;; special cases | |
((eq? x computable-one) | |
(global-return computable-one computable-one)) | |
((eq? x computable-negative-one) | |
(global-return | |
x | |
(lambda (n) | |
(if (odd? n) | |
computable-negative-one | |
computable-one)))) | |
((eq? x computable-zero) | |
(global-return | |
x | |
(lambda (n) | |
(cond ((positive? n) | |
computable-zero) | |
((zero? n) | |
computable-one) | |
(else | |
;; (negative? n) | |
(error "(computable-expt computable-zero negative-number): " n))))) ) | |
;; general case | |
(else | |
(let ((local-exponent-table | |
(make-table weak-keys: #t weak-values: #t test: eqv?))) | |
(define (local-return n closure) | |
(table-set! local-exponent-table n closure) | |
closure) | |
;; this is a bit tricky | |
(letrec ((result | |
(lambda (n) | |
(cond | |
;; if you find n in the table for this x, use it | |
((table-ref local-exponent-table n #f)) | |
;; some special cases | |
((zero? n) | |
(local-return n computable-one)) | |
((= n 1) | |
(local-return n x)) | |
;; general case | |
;; compute one step of the exponential computation | |
;; calling the result for this x when needed | |
((negative? n) | |
(local-return n (computable-inverse (result (- n))))) | |
((even? n) | |
(local-return n (computable-square (result (quotient n 2))))) | |
(else | |
(local-return n (computable-* x (computable-square (result (quotient n 2)))))))))) | |
(global-return x result)))))))) | |
(define (computable-expt x n) | |
((basic-expt x) n)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment