Last active
August 29, 2015 14:16
-
-
Save osamu/81d99bf38c76078ddaf6 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
require 'minitest/unit' | |
module Enumerable | |
def foldr(*args, &block) | |
case args.count | |
when 2 | |
init, method = args | |
when 1 | |
if block_given? | |
init = args.first | |
else | |
method = args.first | |
end | |
end | |
lst = self.dup | |
init = lst.pop unless init | |
if lst.empty? | |
init | |
else | |
if method | |
(lst.shift).send(method, lst.foldr(init, method, &block)) | |
elsif block_given? | |
block.call(lst.shift, lst.foldr(init, &block)) | |
else | |
raise StandardError.new("method argument or block needed") | |
end | |
end | |
end | |
end | |
class TestFoldr < MiniTest::Unit::TestCase | |
def setup | |
@list = [1.0, 2.0, 3.0] | |
end | |
def test_sum | |
assert_equal 6, @list.foldr(0, :+) | |
assert_equal 6, @list.foldr(0) { |a, b| a + b } | |
assert_equal 6, @list.foldr(:+) | |
assert_equal 6, @list.foldr { |a,b| a + b } | |
end | |
def test_div | |
assert_equal 1.5, @list.foldr(1.0, :/) | |
assert_equal 1.5, @list.foldr(1.0) { |a, b| a / b } | |
assert_equal 1.5, @list.foldr(:/) | |
assert_equal 1.5, @list.foldr { |a,b| a / b } | |
end | |
def test_product | |
assert_equal 6, @list.foldr(1.0, :*) | |
assert_equal 6, @list.foldr(1.0) { |a, b| a * b } | |
assert_equal 6, @list.foldr(:*) | |
assert_equal 6, @list.foldr { |a,b| a * b } | |
end | |
end | |
MiniTest::Unit.autorun |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
reverse.injectしたら最短ですね。http://www.dzone.com/snippets/foldr-and-foldl-ruby