Last active
October 27, 2022 12:29
-
-
Save sylph01/ad89335b6c2be1d6bc3fa48b80797513 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Haskellの
scanl
に相当する何かを生やせばよさそう。