Exercise

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

Student Response

1
2
3
4
5
6
7
(define (sum-of-squares x y)
  (+ (* x x) (* y y)))

(define (sum-of-squares-of-two-largest x y z)
  (cond ((and (<= x y) (<= x z)) (+ (* y y) (* z z)))
        ((and (<= y x) (<= y z)) (+ (* x x) (* z z)))
        (else (+ (* x x) (* y y)))))

Teacher Evaluation

Evaluation

Explain this code

Let me explain the Scheme code from the main file:

1
2
3
4
5
6
7
(define (sum-of-squares x y)
  (+ (* x x) (* y y)))

(define (sum-of-squares-of-two-largest x y z)
  (cond ((and (<= x y) (<= x z)) (+ (* y y) (* z z)))
        ((and (<= y x) (<= y z)) (+ (* x x) (* z z)))
        (else (+ (* x x) (* y y)))))

This code defines two functions:

  1. sum-of-squares: Takes two parameters x and y and returns the sum of their squares
1
2
(define (sum-of-squares x y)
  (+ (* x x) (* y y)))
  1. sum-of-squares-of-two-largest: Takes three parameters x, y, and z and returns the sum of squares of the two largest numbers using conditional logic:
1
2
3
4
(define (sum-of-squares-of-two-largest x y z)
  (cond ((and (<= x y) (<= x z)) (+ (* y y) (* z z)))
        ((and (<= y x) (<= y z)) (+ (* x x) (* z z)))
        (else (+ (* x x) (* y y)))))

The logic works as follows:

  • First condition: If x is less than or equal to both y and z, then y and z are the two largest numbers
  • Second condition: If y is less than or equal to both x and z, then x and z are the two largest numbers
  • Else (default case): If neither of above conditions are true, then x and y must be the two largest numbers

The function uses:

  • cond for multiple condition checking
  • and for combining boolean conditions
  • <= for comparison
  • Basic arithmetic operators (+, *)

This is a good example of using conditional logic in Scheme to solve a mathematical problem. The code is concise but effective in finding and operating on the two largest numbers from three inputs.