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

...次のポイントに進みます。フォームの特定の条件に複数の式が必要な場合は、たとえば、の各ブランチに1つの式しか記述できないことに注意してください。 :ififbegin

(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 に答える