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) => 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?
1 Answer 1
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.
-
1\$\begingroup\$ I disagree with you on the
where
-- you always need to read thewhere
in order to understand the code above it, there's noting strange about this code. \$\endgroup\$Patrick Collins– Patrick Collins2015年04月07日 07:33:28 +00:00Commented Apr 7, 2015 at 7:33 -
\$\begingroup\$ @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 likeqsort (x:xs) = qsort lessThanX ++ [x] ++ qsort greaterOrEqualX
, which is possible to understand even without thewhere
. \$\endgroup\$Mephy– Mephy2015年04月07日 11:39:35 +00:00Commented Apr 7, 2015 at 11:39