Recursion 为什么这个尾部递归函数要复杂得多?

Recursion 为什么这个尾部递归函数要复杂得多?,recursion,racket,tail-recursion,Recursion,Racket,Tail Recursion,所以,我在摆弄一些基础数学,我想要一个函数在基之间转换 我写了这个函数: (define (convert-base from to n) (let f ([n n]) (if (zero? n) n (+ (modulo n to) (* from (f (quotient n to))))))) 它适用于我所有的个人测试base 10中的功能将非常好 让我困惑的是,当我试图使函数尾部递归时,我最终遇到了这样的混乱局面(我为SO的好处添加了一些空格

所以,我在摆弄一些基础数学,我想要一个函数在基之间转换

我写了这个函数:

(define (convert-base from to n)
  (let f ([n n])
    (if (zero? n)
        n
        (+ (modulo n to) (* from (f (quotient n to)))))))
它适用于我所有的个人测试base 10中的功能将非常好

让我困惑的是,当我试图使函数尾部递归时,我最终遇到了这样的混乱局面(我为SO的好处添加了一些空格,因为我的代码通常不清晰或漂亮):

我的问题是,本质上,为什么尾部递归函数要复杂得多?这是不可避免的,是因为问题的性质,还是因为我的疏忽?

事实并非如此:

(定义(将基从转换为n)
(设f([n n][mul 1][res 0])
(如果(零?n)
物件
(f(商n到)(*mul-from)(+res(*mul(模n到щщщщ)))
测试

>(convert-base-y 10 2 10)
1010
>(convert-base-y 10 8 64)
100
事实并非如此:

(定义(将基从转换为n)
(设f([n n][mul 1][res 0])
(如果(零?n)
物件
(f(商n到)(*mul-from)(+res(*mul(模n到щщщщ)))
测试

>(convert-base-y 10 2 10)
1010
>(convert-base-y 10 8 64)
100

谢谢!我以为会有一个更好的方法来接近它,我只是错过了,我只是完全阻止了它。真令人沮丧。这就更有意义了。谢谢!我以为会有一个更好的方法来接近它,我只是错过了,我只是完全阻止了它。真令人沮丧。这就更有意义了。
;e.g. 10 2 10 should output 1010, 10 8 64 should output 100 etc.

(define (convert-base-tail from to n)
  (let f ([n n]
          [acc 0]
          [zeros 0])

    (begin (printf "n is ~a. acc is ~a. zeros are ~a.\n" n acc zeros)

    (cond [(zero? n) (let exp 
                       ([x acc]
                        [shft zeros])
                       (if (zero? shft)
                           x
                           (exp (* x 10) (- shft 1))))]
          [(zero? (modulo n to))
            (if (zero? acc)
                (f (quotient n to) (* acc from) (add1 zeros))
                (f (quotient n to) (* acc from) zeros))]
          [else (f (quotient n to) (+ (* acc from) (modulo n to)) zeros )]))))