recursion - 如何在进入无效错误之前中断递归调用

标签 recursion if-statement scheme racket

(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"))))

代码工作正常直到 (tokes (cdr list))) 到达文件末尾。有人可以告诉我如何防止这种情况发生吗?我是 Scheme 的新手,所以如果问题很荒谬,请原谅我。

最佳答案

您必须确保在每种情况下推进递归(基本情况除外,当列表为 null 时)。在您的代码中,您没有对 (write "other") 案例进行递归调用。另外,当有多个条件要测试时,你应该使用 cond,让我用一个例子来解释 - 而不是这个:

(if condition1
    exp1
    (if condition2
        exp2
        (if condition3
            exp3
            exp4)))

最好这样写,它的可读性更高,而且还有一个额外的好处,即您可以在每个条件后编写多个表达式, 而无需使用 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 形式的给定条件,您必须用 begin 包围它们,例如:

(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))

回到你的问题 - 这是一般的想法,填空:

(define (tokes list)
  (cond ((null? list)
         (write "empty"))
        ((operator? (car list))
         (write "operator")
         <???>)   ; advance on the recursion
        (else
         (write "other")
         <???>))) ; advance on the recursion

关于recursion - 如何在进入无效错误之前中断递归调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10468814/

相关文章:

Javascript IF 与 OR 一起使用

scheme - 类似于 SICP 中的 "picture language"的小语言

Python 返回空列表

javascript - IF/Else 条件对 addEventListener/removeEventListener 没有影响

Java解析二叉树结构

Java编译器代码优化违反if条件?

scheme - "How to Design Programs"(HTDP) 第一版和第二版的区别

tree - 算术树的前、中、后顺序 [方案/ Racket ]

java - 并发修改异常——设置数组元素

javascript - 递归遍历树以创建面包屑列表