What is the ‘pythonic’ equivalent to the ‘fold’ function from functional programming?

The Pythonic way of summing an array is using sum. For other purposes, you can sometimes use some combination of reduce (from the functools module) and the operator module, e.g.: def product(xs): return reduce(operator.mul, xs, 1) Be aware that reduce is actually a foldl, in Haskell terms. There is no special syntax to perform folds, … Read more

foldl is tail recursive, so how come foldr runs faster than foldl?

Welcome to the world of lazy evaluation. When you think about it in terms of strict evaluation, foldl looks “good” and foldr looks “bad” because foldl is tail recursive, but foldr would have to build a tower in the stack so it can process the last item first. However, lazy evaluation turns the tables. Take, … Read more

Writing foldl using foldr

Some explanations are in order! What is the id function for? What is the role of? Why should we need it here? id is the identity function, id x = x, and is used as the equivalent of zero when building up a chain of functions with function composition, (.). You can find it defined … Read more

Difference between reduce and foldLeft/fold in functional programming (particularly Scala and Scala APIs)?

reduce vs foldLeft A big big difference, not mentioned in any other stackoverflow answer relating to this topic clearly, is that reduce should be given a commutative monoid, i.e. an operation that is both commutative and associative. This means the operation can be parallelized. This distinction is very important for Big Data / MPP / … Read more