如何在进入void错误之前中断递归调用

Cee*_*los 3 recursion scheme if-statement 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"))))
Run Code Online (Sandbox Code Playgroud)

代码工作得很好直到(tokes(cdr list)))到达文件的末尾.有人可以告诉我如何防止这种情况.我是Scheme的新手,所以如果这个问题很荒谬,我会原谅我.

Ósc*_*pez 6

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

(if condition1
    exp1
    (if condition2
        exp2
        (if condition3
            exp3
            exp4)))
Run Code Online (Sandbox Code Playgroud)

更好地编写它,更具可读性,并且具有额外的好处,您可以在每个条件之后编写多个表达式无需使用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
Run Code Online (Sandbox Code Playgroud)

...这引导我到下一点,要知道你只能为每个分支写一个表达式if,如果if表格中给定条件需要多个表达式,那么你必须用a围绕它们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))
Run Code Online (Sandbox Code Playgroud)

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

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