What is the slickest, most Ruby-like way of calculating the cumulative sum of an array?
Example:
[1,2,3,4].cumulative_sum
should return
[1,3,6,10]
What is the slickest, most Ruby-like way of calculating the cumulative sum of an array?
Example:
[1,2,3,4].cumulative_sum
should return
[1,3,6,10]
The Haskell function we want is scanl, not scanr.
class Array
def scanl(init)
self.reduce([init]) { |a, e| a.push(yield(a.last, e)) }
end
end
[1,2,3,4].scanl(0) { |a, b| a + b }[1..-1]
=> [1, 3, 6, 10]