Last active
November 24, 2019 16:47
-
-
Save sunaot/d70065006fe9de5a1e16180ce6220d14 to your computer and use it in GitHub Desktop.
パターンマッチで fold してみた
This file contains hidden or 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
def fold(init, list, &block) | |
case list | |
in [] | |
init | |
in [x, *xs] | |
fold(block.call(init, x), xs, &block) | |
else | |
raise ArgumentError.new("Array is expected but #{list.inspect} is given") | |
end | |
end | |
def sum(list) | |
fold(0, list, &:+) | |
end | |
puts sum [1,2,3,4,5] #=> 15 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment