Search code examples
schemesicp

What causes an unbound variable error in Scheme?


I've started out with SICP and I'm new to Scheme. I've tried debugging this piece of code and even compared it to similar solutions.

(def (myFunc x y z)
    (cond ((and (<= x y) (<= x z)) (+ (* y y) (* z z)))
          ((and (<= y x) (<= y z)) (+ (* x x) (* z z)))
          (else (+ (* x x) (* y y)))))

This function returns the sum of the squares of two largest numbers.

When I run this, the interpreter gives out ";Unbound variable: y". Could you please explain the cause behind this error?

Help is greatly appreciated :)


Solution

  • The function-defining primitive in Scheme is called define, not def.

    As it is, the whole (def ...) expression was treated as a function call to def. So its arguments' values needed to be found. The first argument (myFunc x y z) is a function call so its argument values needed to be found. Apparently your implementation wanted to find out the value of y first.

    The R5RS standard says "The operator and operand expressions are evaluated (in an unspecified order) and the resulting procedure is passed the resulting arguments."

    It is likely your implementation chooses the rightmost argument first, which leads to (<= x y) being evaluated first (because of special rules of evaluating the cond and and special forms), with y in its rightmost position.