Skip to content

Instantly share code, notes, and snippets.

@sylph01
Last active October 27, 2022 12:29
Show Gist options
  • Save sylph01/ad89335b6c2be1d6bc3fa48b80797513 to your computer and use it in GitHub Desktop.
Save sylph01/ad89335b6c2be1d6bc3fa48b80797513 to your computer and use it in GitHub Desktop.
a = [1, 2, 3, 4, 5]
class Array
def cumulative_sum(default = 0, &block)
block ||= ->(n){n}
a = [default]
for i in 1 .. (self.length)
a[i] = a[i - 1] + block.(self[i - 1])
end
return a
end
def scanl(default = nil, &block)
if default.nil?
a = [self[0]]
for i in 1 .. self.length - 1
a[i] = block.(a[i-1], self[i])
end
else
a = [default]
for i in 1 .. self.length
a[i] = block.(a[i-1], self[i-1])
end
end
return a
end
end
a.cumulative_sum # => [0, 1, 3, 6, 10, 15]
a.cumulative_sum(1) # => [1, 2, 4, 7, 11, 16]
a.cumulative_sum(0) { |x| x ** 2 } # => [0, 1, 5, 14, 30, 55]
@sylph01
Copy link
Author

sylph01 commented Oct 13, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment