我不确定尾递归和一般递归的区别。下面的代码为什么不是尾递归,怎样才能使其成为尾递归?
(define (decode bits tree)
(define (decode-1 bits current-branch)
(if (null? bits)
'()
(let ((next-branch
(choose-branch (car bits) current-branch)))
(if (leaf? next-branch)
(cons (symbol-leaf next-branch)
(decode-1 (cdr bits) tree))
(decode-1 (cdr bits) next-branch)))))
(decode-1 bits tree))
下面的代码(关于尾递归过程)我做错了什么?
(define (decode2 bits tree)
(define (decode-1 bits current-branch res)
(if (null? bits)
(reverse res)
(let ((next-branch
(choose-branch (car bits) current-branch)))
(if (leaf? next-branch)
(decode-1 (cdr bits) tree (cons (symbol-leaf next branch) res))
(decode-1 (cdr bits) tree res)))))
(decode-1 '() tree res))
for
或while
循环,所以递归被用于迭代,但在C/C ++中,您根本不会将迭代与递归等同 ¯_(ツ)_/¯ 但是在我看来,这是旧的FP文献中一种相当常见的惯例。 - Morten Jensen