HiveBrain v1.2.0
Get Started
← Back to all entries
patternModerate

Sum of squares of two largest of three numbers

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
threenumberssquareslargesttwosum

Problem

Given the following problem (SICP Exercise 1.3):


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

I wrote the following (somewhat clumsy) solution in Scheme. How can I make it better?

(define (greatest-two a b c)
  (cond ((> a b) (cond ((> b c) (list a b))
                       (else (list a c))))
        ((> a c) (cond ((> c b) (list a c))
                       (else (list a b))))
        (else (list b c))))

(define (square x) (* x x))
(define (sum-of-squares a b) (+ (square a) (square b)))
(define (f a b c)
  (apply sum-of-squares (greatest-two a b c)))

Solution

Scheme is a lot more functional than Common Lisp. The way you can apply that to this situation is by making more use of passing functions around (to the point that this problem is almost a one-liner). For the puzzle as written, I'd do something like

(define (big-squares a b c)
   (apply + (map (lambda (n) (* n n))
                 (take (sort (list a b c) >) 2))))


If you wanted to decompose it properly into named functions

(define (square num) (expt num 2))
(define (sum num-list) (apply + num-list))
(define (two-biggest num-list) (take (sort num-list >) 2))

(define (big-squares a b c) (sum (map square (two-biggest (list a b c)))))


If you wanted to go completely overboard, also toss in

(define (squares num-list) (map square num-list))


which would let you define big-squares as

(sum (squares (two-biggest (list a b c))))


(code above in mzscheme)

Code Snippets

(define (big-squares a b c)
   (apply + (map (lambda (n) (* n n))
                 (take (sort (list a b c) >) 2))))
(define (square num) (expt num 2))
(define (sum num-list) (apply + num-list))
(define (two-biggest num-list) (take (sort num-list >) 2))

(define (big-squares a b c) (sum (map square (two-biggest (list a b c)))))
(define (squares num-list) (map square num-list))
(sum (squares (two-biggest (list a b c))))

Context

StackExchange Code Review Q#1395, answer score: 11

Revisions (0)

No revisions yet.