Recursion 如何在进入无效错误之前中断递归调用
代码在(tokes(cdrlist))到达文件末尾之前工作正常。有人能给我一个建议,告诉我怎样才能防止这种情况发生吗。我是Scheme的新手,如果这个问题很荒谬,请原谅。您必须确保在每种情况下推进递归(基本情况除外,当列表为Recursion 如何在进入无效错误之前中断递归调用,recursion,if-statement,scheme,racket,Recursion,If Statement,Scheme,Racket,代码在(tokes(cdrlist))到达文件末尾之前工作正常。有人能给我一个建议,告诉我怎样才能防止这种情况发生吗。我是Scheme的新手,如果这个问题很荒谬,请原谅。您必须确保在每种情况下推进递归(基本情况除外,当列表为null时)。在代码中,您没有对(write“other”)案例进行递归调用。另外,当有几个条件需要测试时,您应该使用cond,让我用一个例子来解释-而不是这个: (define l '(* - + 4)) (define (operator? x) (or (eq
null
时)。在代码中,您没有对(write“other”)
案例进行递归调用。另外,当有几个条件需要测试时,您应该使用cond
,让我用一个例子来解释-而不是这个:
(define l '(* - + 4))
(define (operator? x)
(or (equal? '+ x) (equal? '- x) (equal? '* x) (equal? '/ x)))
(define (tokes list)
(if (null? list)(write "empty")
(if (operator? (car list))
((write "operator")
(tokes (cdr list)))
(write "other"))))
更好地编写它,更具可读性,并具有额外的好处,即您可以在每个条件后编写多个表达式,而无需使用begin
表单:
(if condition1
exp1
(if condition2
exp2
(if condition3
exp3
exp4)))
。。。这将我引向下一点,请注意,对于if
的每个分支,您只能编写一个表达式,如果if
表单中的给定条件需要多个表达式,则必须用begin
将其包围,例如:
(cond (condition1 exp1) ; you can write additional expressions after exp1
(condition2 exp2) ; you can write additional expressions after exp2
(condition3 exp3) ; you can write additional expressions after exp3
(else exp4)) ; you can write additional expressions after exp4
回到你的问题——这里是总体思路,填空:
(if condition
; if the condition is true
(begin ; if more than one expression is needed
exp1 ; surround them with a begin
exp2)
; if the condition is false
(begin ; if more than one expression is needed
exp3 ; surround them with a begin
exp4))
(定义(托克斯列表)
(条件((空?列表)
(写“空”))
((操作员?(车辆列表))
(写“操作员”)
)递归算法的进展
(其他
(写“其他”)
))) ; 递归算法研究进展
该代码真的可以工作到文件结束吗?在这行:((write“operator”)(tokes…)
您正在将(write“operator”)
的结果应用到(tokes…)
-这应该会抛出错误(我尝试时会这样做),这就是我的意思。我想我没有充分解释我自己。一旦cdr文件接收到eof,它就给出了正确的无效错误。谢谢你,奥斯卡,你在我所有的问题上都帮了我很大的忙!
(define (tokes list)
(cond ((null? list)
(write "empty"))
((operator? (car list))
(write "operator")
<???>) ; advance on the recursion
(else
(write "other")
<???>))) ; advance on the recursion