3
(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 的新手,所以如果这个问题很荒谬,我会原谅我。

4

1 回答 1

6

您必须确保在每种情况下都推进递归(基本情况除外,当列表为 时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,如果表单中的给定条件需要多个表达式,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
于 2012-05-06T07:21:41.240 回答