Skip to content

Instantly share code, notes, and snippets.

@sunaot
Last active November 24, 2019 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunaot/d70065006fe9de5a1e16180ce6220d14 to your computer and use it in GitHub Desktop.
Save sunaot/d70065006fe9de5a1e16180ce6220d14 to your computer and use it in GitHub Desktop.
パターンマッチで fold してみた
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