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.


My answer is this:

    import Data.List(sort)

    sumSquareLargest :: (Ord n, Floating n) =&gt; n -&gt; n -&gt; n -&gt; 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.