Question

I'm currently going through exercise 1.3 of the sicp book. Here's the description of the problem:

Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.

I tried to solve it with the following code

(define (square x) (* x x))

(define (sq2largest a b c)
        ((define large1 (if (> a b) a b)) 
         (define small  (if (= large1 a) b a))
         (define large2 (if (> c small) c small))
         (+ (square large1) (square large2))))

When I ran it in mit-scheme, I got the following error:

;Can't bind name in null syntactic environment: large1 #[reserved-name-item 13]

Googling this error doesn't yield many results. Does anyone know what's wrong with my code? (I'm not familiar with Scheme)

Was it helpful?

Solution 2

You have too many brackets. If you took out the extra brackets around the internal defines, things should work a lot better.

OTHER TIPS

I'll try to break down the structure of your sq2largest procedure:

The basic structure is:

(define (sq2largest a b c)
    ; Body)

The Body you wrote is:

((define large1 (if (> a b) a b)) ; let this be alpha
 (define small  (if (= large1 a) b a)) ; let this be bravo
 (define large2 (if (> c small) c small)) ; let this be charlie
 (+ (square large1) (square large2)) ; let this be delta) ; This parentheses encloses body

So, the Body is structured as:

(alpha bravo charlie delta)

Which translates to: "Pass bravo, charlie and delta as arguments to alpha."

Now, alpha is being told to take a bunch of arguments, but inside the namespace reserved for large1, no provision was made for any argument... i.e. scheme encounters a null syntactic environment where it cannot bind any variable.

Parentheses are significant in Scheme (and most, if not all, Lisps) because they define the scope of a procedure and enforce[1] the order of application of operations.

[1] "No ambiguity can arise, because the operator is always the leftmost element and the entire combination is delimited by the parentheses." http://mitpress.mit.edu/sicp/full-text/sicp/book/node6.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top