"Euler #6 : Squares and Sums"

by Nicolas Wu


Posted on 5 August 2010

Tags: Haskell, Euler


This week’s Project Euler puzzle is extremely simple compared to the ones we’ve had so far:

What is the difference between the sum of the squares and the square of the sums?

We start this answer by defining square, which is simply the function that squares its argument:

> square :: Int -> Int
> square x = x * x

Our answer falls out quite directly, and the question asks for the value of the difference between the sum of the squares and the square of the sums of the numbers between 1 and 100:

> euler6 = abs $ (square . sum) xs - (sum . (map square)) xs
>   where
>     xs = [1 .. 100]

Here we’ve used the function abs that returns the absolute (positive) value of a number:

abs :: Int -> Int

Strictly speaking, we didn’t need to use this since the values returned are always positive, but it’s a useful function worth knowing. Even more useful is the function ($), which we’ve put just after abs. This function applies its left argument to the expression to its right. Here’s its type:

($) :: (a -> b) -> a -> b

This operator is given the least precedence when working out how it binds, which basically makes it useful for avoiding large parenthesised expressions. You should think of it as wrapping brackets around its right argument as far as it can.

Summary

There really isn’t much to summarize this time, except for squares of lists … oh, and:

  • The ($) operator is useful for avoiding lots of brackets.

Comments