Skip to content

Instantly share code, notes, and snippets.

@osamu
Last active August 29, 2015 14:16
Show Gist options
  • Save osamu/81d99bf38c76078ddaf6 to your computer and use it in GitHub Desktop.
Save osamu/81d99bf38c76078ddaf6 to your computer and use it in GitHub Desktop.
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
@osamu
Copy link
Author

osamu commented Mar 12, 2015

reverse.injectしたら最短ですね。http://www.dzone.com/snippets/foldr-and-foldl-ruby

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