[racket] Puzzled with tail-recursion conversion

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Wed Feb 15 14:02:26 EST 2012

If you systematically apply cps and then accumulator transformations, you get this: 

(define (pi3 accuracy)
  (let helper ((k 0))
    (let ((this (formula k)))
      (if (< (abs this) accuracy)
          (+ this (helper (+ k 1)))))))

(pi3 .1)

(define (pi3-cps accuracy)
  (let helper ((k 0) (c (lambda (x) x)))
    (let ((this (formula k)))
      (if (< (abs this) accuracy)
          (c this)
          (helper (+ k 1) (lambda (v) (c (+ this v))))))))

(pi3-cps .1)

(define (pi3-accu accuracy)
  (let helper ((k 0) (c 0))
    (let ((this (formula k)))
      (if (< (abs this) accuracy)
          (+ c this)
          (helper (+ k 1) (+ c this))))))

(pi3-accu .1)

Now when you compare the result of that with yours: 

(define (pi4 accuracy)
  (let helper ((k 1) (this (formula 0)))
    (if (< (abs this) accuracy)
        (helper (+ k 1) (+ this (formula k))))))

you immediately see why yours fails. 

;; --- 

I would worry about accuracy because you are switching the direction of addition when you apply the accu transform, but perhaps you know why this doesn't matter for your context. 

Posted on the users mailing list.