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

Why can't I use 'and' as the predicate in my 'cond' expression?

I am a self-taught software engineer who is trying to fill in their CS knowledge gaps by following the SICP book which comes highly recommended. I’m having trouble with one of the first exercises and I’m pretty sure it’s a syntax problem, but I can’t figure it out.

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

#lang sicp

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

(define (squaresum x y) (+ (square x) (square y)))

(define
  (squaresumlg x y z)
  (cond
    (and (> x z) (> y z)) (squaresum x y)
    (and (> x y) (> z y)) (squaresum x z)
    (and (> y x) (> z x)) (squaresum y z)))

(squaresumlg 1 2 3)

To run this I am using DrRacket with the ‘sicp’ package. The and expressions run just fine on their own, but inside the cond expression, I receive the error:

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

and: bad syntax in: and

Can someone please tell me where I’ve gone wrong in my program? If you have any tips on how I could do this more efficiently please let me know.

>Solution :

You’re missing some parentheses, each condition in a cond is expected to be surrounded by (). You’re also missing a case, think about it – what happens if two of the numbers are the same? This should fix the missing parentheses error:

(define (squaresumlg x y z)
  (cond
    ((and (> x z) (> y z)) (squaresum x y))
    ((and (> x y) (> z y)) (squaresum x z))
    ((and (> y x) (> z x)) (squaresum y z))
    (else (error "oops, you forgot to handle this case!"))))

And this example demonstrates that you still need to work out the logic for the edge cases (always use an else clause!). Perhaps using >= will help?

(squaresumlg 1 1 3)
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