reduce

taman9333 · @taman9333 · almost 3 years

Functional way for implementing reduce.

it invokes function for each element in the enumerable with the accumulator.

def reduce(enum, acc, func)
reduce_aux = lambda do |acc, enum|
if enum.empty?
acc
else
reduce_aux.call(func.call(acc, enum.first), enum.drop(1))
end
end
reduce_aux.call(acc, enum)
end
# Example
# irb> reduce([1,2,3], 2, -> (x, y) {x+y})
# => 8
1 · 0 · 0