我需要一些帮助来理解尾递归
#lang racket
(define (lista x)
(printf(length(cons x (lista (read)))))
)
(lista (read))
我不知道如何结束链表的循环,然后获取长度并打印此数字。
因此,例如,如果我输入了
2
1
3
5
7
5
10
它必须打印7,但是编译器始终会显示消息超时,因此我不知道我是否在正确读取输入内容,或者还有另一种方法?
您正在做的事情没有任何意义(我将在下面解释原因)。如果使用length
,则可以立即返回列表的长度。之所以具有无限循环,是因为您没有停止条件(即,当列表null?
结束递归时)。
我想这是一项作业,需要您手动执行,因此不使用length
。
(define (lngth lst)
(if (null? lst) ; Did we checked the whole list already?
0 ; This will put an end to the recursion !
(+ 1 ; Tail recursive call, we add 1 because we call ourselve recusrively with the cdr of the list (hence with a list that is one shorter)
(lngth (cdr lst)))))
现在您可以调用此过程,(lngth '(1 2 3 4 5))
将返回5。
(define (lista x)
(printf
(length
(cons x
(lista (read))))))
您的尝试有一些问题。最大的问题是它缺少停止条件,这是循环不断的原因(循环不断提示用户输入)。现在lista
,由于,您将始终会一次又一次地递归调用自身(define (lista x) ... (cons x (lista ...)))
。
就像我在上面说的,其余的代码实际上没有任何意义。您正在使用cons
而不是cdr
遍历列表,并且正在使用length
而不是为(+ 1 (recursive call))
列表的当前元素添加一个。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句