我在Racket中编写了两个不同的函数来确定数字列表是否升序:
(define (ascending list)
(if (<= (length list) 1)
#t
(and (< (car list) (car (cdr list))) (ascending (cdr list)))))
(define (ascending-tail list)
(ascending-tail-helper #t list))
(define (ascending-tail-helper prevBool rest)
(if (<= (length rest) 1)
prevBool
(ascending-tail-helper (and prevBool (< (car rest) (car (cdr rest)))) (cdr rest))))
我曾经花费很长时间来确定第一个升序函数是否是尾递归,所以我重新编写了它,使用我认为是尾递归的方式。
我回顾后认为第一个函数不是尾递归的原因是,在每次递归的每个级别上,函数都将等待“and”语句中的第二个参数返回,然后才能计算布尔表达式。相反,在ascending-tail-helper中,我能够在进行递归调用之前计算小于表达式。
这个理解正确吗?还是让我比以前更困惑了?