I Like Programming

Reduce by Any Other Name

One of my favorite functions is `reduce`.  It’s the perfect way to represent anything like sum, product, factorial, reverse, that walks along a list accumulating the values it finds.  Unfortunately, it’s hard to share my love of reduce when every language calls it something different.  Observe:

# Python - reduce
# reduce(function, iterable[, initializer])
def factorial(n):
return reduce(lambda acc,x: acc*x, range(1,n), 1)

# Ruby - inject
# Enumerable#inject(init) {|result, item| ...}
def factorial(n)
(1..n).inject(1) {|acc,x| acc*x}
end

-- Haskell - fold
-- foldl :: (a -> b -> a) -> a -> [b] -> a
factorial n = foldl (*) 1 [1..n]

// C# - Aggregate
// Enumerable.Aggregate<(Of <(TSource, TAccumulate>)>)
//   Method (IEnumerable<(Of <(TSource>)>),
//     TAccumulate, Func<(Of <(TAccumulate, TSource, TAccumulate>)>))
// (This type signature is pretty ridiculous)
int factorial(int n){
return Enumerable.Range(1, n).Aggegate(1, (acc,x) => acc*x);
}