Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't my solution to SICP Exercise 1.3 work?

Tags:

scheme

sicp

I just began working through SICP and I'm doing the first problem set, namely Exercise 1.3: "Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers."

(define (toptwosq x y z)
  (cond ((and (> x y) (> z y))) (+ (* x x) (* z z))
        ((and (> y x) (> z x))) (+ (* y y) (* z z))
        ((and (> x z) (> y z))) (+ (* x x) (* y y))))

When I run this, I get pretty odd results(none of which get me the sum of the squares of the largest two numbers). I've found other solutions that work and I understand why they work...but why doesn't mine?

like image 666
Parmy Avatar asked Dec 05 '25 19:12

Parmy


1 Answers

You're closing the cond clauses too early.

((and (> x y) (> z y))) is your first cond clause, which will return #t if true and #f otherwise, and if true will make the value of the cond to be #t.

(+ (* x x) (* z z)) is your second cond clause, which will always return the value of the sum of the square of x and the square of z, making the cond statement return that value as any value other than #f is considered and true. Sometimes it's useful to exploit this one-part clause, but most of the time you want to use two part clauses.

(define (toptwosq x y z)
  (cond ((and (> x y) (> z y)) (+ (* x x) (* z z)))
        ((and (> y x) (> z x)) (+ (* y y) (* z z)))
        ((and (> x z) (> y z)) (+ (* x x) (* y y)))))

and you really should have an else clause

(else (+ (square x) (square y)) 

As none of the cases you've put out so far will catch the case of x y and z being the same value.

Get an editor that does parenthesis matching and you life will become easier.

like image 188
WorBlux Avatar answered Dec 09 '25 21:12

WorBlux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!