Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summation notation in Haskell

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?

like image 310
MattyW Avatar asked Aug 27 '09 06:08

MattyW


People also ask

What is the type of the function sum Haskell?

It is, indeed, polymorphism, though not in this way (see the P.S. at the end of this answer). Note that... ... is already polymorphic in the type of the numbers being summed, so it would work with, for instance, lists of Integer and lists of Double .


2 Answers

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.

like image 200
ire_and_curses Avatar answered Oct 07 '22 04:10

ire_and_curses


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
like image 36
Paige Ruten Avatar answered Oct 07 '22 02:10

Paige Ruten