Search code examples
schemecalculatormit-scheme

whats is wrong with this two operator calculator?


I want to write a procedure named twoOperatorCalculator which will calculate left-associative infix addition and subtraction operations. Operations are given as a list and the output should be the result of these operations. Below is a sample output for this procedure:

1 ]=> (twoOperatorCalculator '(1 + 15 − 32/5 + −2))'<br/>
Value : 38/5<br/>

I tried so much but I could not find my fault. Error is like

1 ]=> (twooperatorcalculator '(1+2-3+2))'

;The object (1+2-3+2) is not applicable.

MY CODE

(define twooperatorcalculator 
  (lambda (exp) (
    (cond
      ((null? exp) 0)
      ((null? (cdr (cdr exp))) (car exp))
      ((eq? #\+ (cadr exp)) (+ (car (exp)) twooperatorcalculator (cdr (cdr exp))))
      ((eq? #\- (cadr exp)) (- (car (exp)) twooperatorcalculator (cdr (cdr exp))))))))

Solution

  • (exp)
    

    You are enclosing exp in parentheses, which means you are asking the interpreter to call the function currently bound to exp. But exp is a list, and cannot be called. You need to remove parentheses.

    (... twooperatorcalculator ...)
    

    Right after that, you have twooperatorcalculator that is not enclosed in parentheses, which means that you want to evaluate the symbol. Here it will be bound to a function object, which is not meaningful for a + operation. You need to enclose it in parentheses to call the function recursively.