Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what's wrong with this basic scheme function

I’m trying to write a scheme function that does the following (taken from SICP):

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

Here’s my attempt:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(define (square-sum-larger a b c)
  (cond ((and (< a b) (< a c))) (+ (* b b) (* c c)))
  (cond ((and (< b c) (< b a))) (+ (* a a) (* c c)))
  (cond ((and (< c a) (< c b))) (+ (* b b) (* a a)))
)

When I enter this into the biwa scheme interpreter, I get the following:

(square-sum-larger 4 5 6)
16

Since 4 is less than 5 and 6, shouldn’t the first condition be evaluated, meaning that the sum of the squares of 5 and 6 should be returned?

>Solution :

(define (square-sum-larger a b c)
  (cond ((and (< a b) (< a c))) (+ (* b b) (* c c))) ;; this is thrown away
  (cond ((and (< b c) (< b a))) (+ (* a a) (* c c))) ;; this is thrown away
  (cond ((and (< c a) (< c b))) (+ (* b b) (* a a)))
)

Only the last of the three cond does anything useful; the previous cond expressions do not have any side effect, since they perform only calculations, and their value is not used. The are dead code which a Scheme compiler can eliminate entirely.

You probably wanted to combine all of the clauses into a single cond:

(define (square-sum-larger a b c)
  (cond ((and (< a b) (< a c))) (+ (* b b) (* c c))
        ((and (< b c) (< b a))) (+ (* a a) (* c c))
        ((and (< c a) (< c b))) (+ (* b b) (* a a))))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading