sachinrahulsourav
sachinrahulsourav

Reputation: 752

sum of squares of max 2 of 3 SICP exercise

I have written a procedure to compute the sum of squares of the first and second greatest of 3 numbers as below...

    (define (max2of3 x y z)
      (let ((first (max x y))
            (second (max first z)))
        (+ (* first first) (* second second))))

But I am getting an error when i execute it...

[2] (load "max2of3") OK [3] (max2of3 1 2 3)

[VM ERROR encountered!] Variable not defined in lexical environment FIRST

While i do understand the error is caused because the interpreter doesn't recognize the variable 'FIRST', i fail to understand why?

By definition from SICP:

The first part of the let expression is a list of name-expression pairs. When the let is evaluated, each name is associated with the value of the corresponding expression. The body of the let is evaluated with these names bound as local variables

Doesnt that mean 'let' construct declares a variable in the declaration block?

Thanks.

Upvotes: 1

Views: 169

Answers (1)

Karoly Horvath
Karoly Horvath

Reputation: 96286

The problem is that why evaluating (second (max first z))) first is not in scope.

As the definition says, that name is available only in the body of let. At this point, the runtime tries to resolve the name in the outer scope, where it's not defined, hence the error.

Note: a nested let would solve this problem.

Upvotes: 1

Related Questions