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?
On the Wikipedia page about summation it says that the equivalent operation in Haskell
Share
foldlis 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 likefold, the tail-recursive implementation is very efficient. As others have explained,sumis then just a convenient mnemonic forfoldl (+) 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
foldfunctions with simple examples that’s well worth reading.