views:

471

answers:

6

On the Wikipedia page about summation it says that the equivalent operation in Haskell is to use foldl. My question is: Is there any reason why it says to use this instead of sum? Is one more 'purist' than the other, or is there no real difference?

+3  A: 

I don't see where it says anything about Haskell or foldl on that Wikipedia page, but sum in Haskell is just a more specific case of foldl. It can be implemented like this, for example:

sum l = foldl (+) 0 l

Which can be reduced to:

sum = foldl (+) 0
yjerem
Aah, now I see it. I had done a search for 'foldl' but the Wikipedia page uses 'fold'.
yjerem
A: 

There is no difference. That page is simply saying that sum is implemented using foldl. Just use sum whenever you need to calculate the sum of a list of numbers.

Martijn
+1  A: 

As stated by the others, there's no difference. However, a sum-call is easier to read than a fold-call, so I'd go for sum if you need summation.

Christian
+10  A: 

foldl is a general tail-recursive reduce function. Recursion is the usual way of thinking about manipulating lists of items in a functional programming languages, and provides an alternative to loop iteration that is often much more elegant. In the case of a reduce function like fold, the tail-recursive implementation is very efficient. As others have explained, sum is then just a convenient mnemonic for foldl (+) 0 l.

Presumably its use on the wikipedia page is to illustrate the general principle of summation through tail-recursion. But since the Haskell Prelude library contains sum, which is shorter and more obvious to understand, you should use that in your code.

Here's a nice discussion of Haskell's fold functions with simple examples that's well worth reading.

ire_and_curses
+2  A: 

One thing to note is that sum may be lazier than you would want, so consider using foldl'.

Edward Kmett
A: 

The concept of summation can be extended to non-numeric types: all you need is something equivalent to a (+) operation and a zero value. In other words, you need a monoid. This leads to the Haskell function "mconcat", which returns the sum of a list of values of a monoid type. The default "mconcat" of course is defined in terms of "mappend" which is the plus operation.

Paul Johnson