How to break a recursive call before entering a void error

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

The code works just fine til (tokes (cdr list))) comes to the end of the file. Can someone give me a clue how I can prevent this. I am new to Scheme, so I forgive if the question is absurd.

+3
source share
1 answer

You must make sure that recursion is promoted in every case (except for the base case, when the list is null). In code, you are not making a recursive call for the case (write "other"). In addition, you should use condwhen there are several conditions for verification. Let me explain with an example - instead:

(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
+6

All Articles