5
\$\begingroup\$

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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Apr 7, 2015 at 3:11
\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

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.

answered Apr 7, 2015 at 3:30
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented 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 like qsort (x:xs) = qsort lessThanX ++ [x] ++ qsort greaterOrEqualX, which is possible to understand even without the where. \$\endgroup\$ Commented Apr 7, 2015 at 11:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.