Skip to content

Instantly share code, notes, and snippets.

@athos
Created January 18, 2011 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save athos/784338 to your computer and use it in GitHub Desktop.
Save athos/784338 to your computer and use it in GitHub Desktop.
;; 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