# SICP Exercise 1.3: Sum of squares of two largest numbers out of three, Haskell Version

The exercise 1.3 of the book Structure and Interpretation of Computer Programs asks the following:

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

    import Data.List(sort)

sumSquareLargest :: (Ord n, Floating n) => n -> n -> n -> n
sumSquareLargest x y z = b ** 2 + c ** 2 where
[a, b, c] = sort[x, y, z]


Am I doing unnecessary work here? How could I improve this answer, even if only stylistically-speaking?

If you don't need a value, don't bind it, use a wildcard instead.

[a, b, c] = sort [x, y, z] # and btw, add a space after the function name


becomes

[_, b, c] = sort [x, y, z]


Perhaps its just personal preference (I don't use much Haskell myself), but I usually see the where clause in the next line, with an extra tab, like:

sumSquareLargest x y z = b ** 2 + c ** 2
where [_, b, c] = sort [x, y, z]


Moreover, the b and c values are not obvious at first glance, and you need to read the second line before the first. In these cases, a let expression can be a more nice alternative:

sumSquareLargest x y z =
let [_, b, c] = sort [x, y, z]
in b ** 2 + c ** 2


This is a very small function, but consider having more meaningful names for your bindings:

sumSquareLargest x y z =
let [_, medium, maxim] = sort [x, y, z]
in medium ** 2 + maxim ** 2


Also, consider writing some unit tests in a library like QuickCheck.

• I disagree with you on the where -- you always need to read the where in order to understand the code above it, there's noting strange about this code. – Patrick Collins Apr 7 '15 at 7:33
• @PatrickCollins most of the times, the where isn't that relevant, as in you can abstract the values it produces. This is especially true if the bindings have meaningful names. For example, the classic QuickSort implementation is something like qsort (x:xs) = qsort lessThanX ++ [x] ++ qsort greaterOrEqualX, which is possible to understand even without the where. – Mephy Apr 7 '15 at 11:39