Skip to content

Instantly share code, notes, and snippets.

@athos athos/tco.scm
Created Jan 18, 2011

Embed
What would you like to do?
;; 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
You can’t perform that action at this time.