2
votes

I'm having trouble figuring out how to sort out the 2 biggest numbers and return them into the sum of squares procedure. I am struggling to write the code out in Scheme's syntax. I'm trying to write it as cleanly as possible, and I keep running circles in my head and on paper trying to do so. the book describes thinking "procedurally" and I think I'm having trouble with that aspect.

The book provides code for the sum-of-squares and square procedures. I would include my pseudo code but I'm severely lost. Here is the code the book provides:

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

(define (sum-of-squares x y)
  (+ (square x) (square y)))

How to define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers?

3
And your question is ...?rsm
Possible duplicate of SICP Exercise 1.3 request for commentsGAD3R

3 Answers

2
votes

How to define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers?

First you need a name for the procedure. Let's called it sum-of-squares-two-largest.

(define (sum-of-squares-two-largest x y z)
   ...)

It can make use of the sum-of-squares function, but it needs to find the two largest numbers out of x,y,z first.

One way to do this would be to get rid of the smallest number. You could define a helper procedure smallest? a b c that checks that a is the smallest of the 3 numbers by doing (and (<= a b) (<= a c)).

(define (sum-of-squares-two-largest x y z)
   (if (smallest? x y z)
       (sum-of-squares y z)
       (if (smallest? y x z)
           ...]
0
votes

Write the code for min-of-three. Its negative (as in photography) is what you need:

(define (negative-min-of-three a b c)
   (if (<= a b)
       (if (<= a c)
           (..... b ... c .....)
           (..... a ... b .....))
       (if (<= 
   ..........

You can complete the code, and rename it. The clock is ticking!

0
votes

I created two methods to get the largest and the one in the middle for the time being.

(define (largest x y z)
  (cond ((and (> x y) (> x z)) x)
        ((and (> y x) (> y z)) y)
        (else z))
)

(define (mid x y z)
  (cond ((and (> x y) (< x z)) x)
        ((and (> y x) (< y z)) y)
        (else z))
)

(define (square a)
  (* a a)
)

(define (sum-of-two-largest x y z)
  (+ (square (largest x y z)) (square (mid x y z)))
)

(sum-of-two-largest -12 -4 1)