Created
January 18, 2011 12:05
-
-
Save athos/784338 to your computer and use it in GitHub Desktop.
This file contains 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
;; from http://d.hatena.ne.jp/wasabiz/20110118/1295335821 | |
;; 「Pythonで末尾再帰最適化をする。」のScheme版 | |
(define (TCO proc) | |
(let ([first? #t] [continue (list 'CONTINUE)] [args #f]) | |
(lambda args* | |
(if first? | |
(begin | |
(set! first? #f) | |
(let loop ([result (apply proc args*)]) | |
(if (eq? result continue) | |
(loop (apply proc args)) | |
(begin | |
(set! first? #f) | |
result)))) | |
(begin | |
(set! args args*) | |
continue))))) | |
(define sum | |
(TCO (lambda (n acc) | |
(if (= n 0) | |
acc | |
(sum (- n 1) (+ acc n)))))) | |
;; Schemeは何もしなくても末尾呼び出しが最適化されるので、以下でも同じ | |
(define sum | |
(lambda (n acc) | |
(if (= n 0) | |
acc | |
(sum (- n 1) (+ acc n))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment