Search code examples
schemeracketsicp

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:

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)