[前][次][番号順一覧][スレッド一覧]

ruby-changes:42958

From: mrkn <ko1@a...>
Date: Tue, 17 May 2016 22:58:53 +0900 (JST)
Subject: [ruby-changes:42958] mrkn:r55032 (trunk): Implement Enumerable#sum

mrkn	2016-05-17 22:58:46 +0900 (Tue, 17 May 2016)

  New Revision: 55032

  https://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=55032

  Log:
    Implement Enumerable#sum
    
    * enum.c (enum_sum): Implement Enumerable#sum.
    
    * test/ruby/test_enum.rb (test_sum): Test sum for Enumerable.
    
    * test/ruby/test_hash.rb (test_sum): Test sum for Hash.
    
    * test/ruby/test_range.rb (test_sum): Test sum for Range.

  Modified files:
    trunk/ChangeLog
    trunk/enum.c
    trunk/test/ruby/test_enum.rb
    trunk/test/ruby/test_hash.rb
    trunk/test/ruby/test_range.rb
Index: ChangeLog
===================================================================
--- ChangeLog	(revision 55031)
+++ ChangeLog	(revision 55032)
@@ -1,3 +1,13 @@ https://github.com/ruby/ruby/blob/trunk/ChangeLog#L1
+Tue May 17 22:53:00 2016  Kenta Murata  <mrkn@m...>
+
+	* enum.c (enum_sum): Implement Enumerable#sum.
+
+	* test/ruby/test_enum.rb (test_sum): Test sum for Enumerable.
+
+	* test/ruby/test_hash.rb (test_sum): Test sum for Hash.
+
+	* test/ruby/test_range.rb (test_sum): Test sum for Range.
+
 Tue May 17 22:11:41 2016  Tanaka Akira  <akr@f...>
 
 	* object.c, numeric.c, enum.c, ext/-test-/bignum/mul.c,
Index: enum.c
===================================================================
--- enum.c	(revision 55031)
+++ enum.c	(revision 55032)
@@ -3561,6 +3561,153 @@ enum_chunk_while(VALUE enumerable) https://github.com/ruby/ruby/blob/trunk/enum.c#L3561
     return enumerator;
 }
 
+struct enum_sum_memo {
+    VALUE v, r;
+    long n;
+    double f, c;
+    int block_given;
+    int float_value;
+};
+
+static VALUE
+enum_sum_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
+{
+    struct enum_sum_memo *memo = (struct enum_sum_memo *)args;
+    long n = memo->n;
+    VALUE v = memo->v;
+    VALUE r = memo->r;
+    double f = memo->f;
+    double c = memo->c;
+
+    ENUM_WANT_SVALUE();
+
+    if (memo->block_given)
+        i = rb_yield(i);
+
+    if (memo->float_value)
+        goto float_value;
+
+    if (FIXNUM_P(v) || RB_TYPE_P(v, T_BIGNUM) || RB_TYPE_P(v, T_RATIONAL)) {
+        if (FIXNUM_P(i)) {
+            n += FIX2LONG(i); /* should not overflow long type */
+            if (!FIXABLE(n)) {
+                v = rb_big_plus(LONG2NUM(n), v);
+                n = 0;
+            }
+        }
+        else if (RB_TYPE_P(i, T_BIGNUM))
+            v = rb_big_plus(i, v);
+        else if (RB_TYPE_P(i, T_RATIONAL)) {
+            if (r == Qundef)
+                r = i;
+            else
+                r = rb_rational_plus(r, i);
+        }
+        else {
+            if (n != 0) {
+                v = rb_fix_plus(LONG2FIX(n), v);
+                n = 0;
+            }
+            if (r != Qundef) {
+                /* r can be a Integer when mathn is loaded */
+                if (FIXNUM_P(r))
+                    v = rb_fix_plus(r, v);
+                else if (RB_TYPE_P(r, T_BIGNUM))
+                    v = rb_big_plus(r, v);
+                else
+                    v = rb_rational_plus(r, v);
+                r = Qundef;
+            }
+            if (RB_FLOAT_TYPE_P(i)) {
+                f = NUM2DBL(v);
+                c = 0.0;
+                memo->float_value = 1;
+                goto float_value;
+            }
+            else
+                goto some_value;
+        }
+    }
+    else if (RB_FLOAT_TYPE_P(v)) {
+        /* Kahan's compensated summation algorithm */
+        double x, y, t;
+
+      float_value:
+        if (RB_FLOAT_TYPE_P(i))
+            x = RFLOAT_VALUE(i);
+        else if (FIXNUM_P(i))
+            x = FIX2LONG(i);
+        else if (RB_TYPE_P(i, T_BIGNUM))
+            x = rb_big2dbl(i);
+        else if (RB_TYPE_P(i, T_RATIONAL))
+            x = rb_num2dbl(i);
+        else {
+            v = DBL2NUM(f);
+            memo->float_value = 0;
+            goto some_value;
+        }
+
+        y = x - c;
+        t = f + y;
+        c = (t - f) - y;
+        f = t;
+    }
+    else {
+      some_value:
+        v = rb_funcall(v, idPLUS, 1, i);
+    }
+
+    memo->v = v;
+    memo->n = n;
+    memo->r = r;
+    memo->f = f;
+    memo->c = c;
+
+    return Qnil;
+}
+
+
+/*
+ */
+static VALUE
+enum_sum(int argc, VALUE* argv, VALUE obj)
+{
+    struct enum_sum_memo memo;
+
+    if (rb_scan_args(argc, argv, "01", &memo.v) == 0)
+        memo.v = LONG2FIX(0);
+
+    memo.block_given = rb_block_given_p();
+
+    memo.n = 0;
+    memo.r = Qundef;
+
+    if ((memo.float_value = RB_FLOAT_TYPE_P(memo.v))) {
+        memo.f = RFLOAT_VALUE(memo.v);
+        memo.c = 0.0;
+    }
+
+    rb_block_call(obj, id_each, 0, 0, enum_sum_iter_i, (VALUE)&memo);
+
+    if (memo.float_value) {
+        return DBL2NUM(memo.f);
+    }
+    else {
+        if (memo.n != 0)
+            memo.v = rb_fix_plus(LONG2FIX(memo.n), memo.v);
+        if (memo.r != Qundef) {
+            /* r can be a Integer when mathn is loaded */
+            if (FIXNUM_P(memo.r))
+                memo.v = rb_fix_plus(memo.r, memo.v);
+            else if (RB_TYPE_P(memo.r, T_BIGNUM))
+                memo.v = rb_big_plus(memo.r, memo.v);
+            else
+                memo.v = rb_rational_plus(memo.r, memo.v);
+        }
+        return memo.v;
+    }
+}
+
 /*
  *  The <code>Enumerable</code> mixin provides collection classes with
  *  several traversal and searching methods, and with the ability to
@@ -3633,6 +3780,7 @@ Init_Enumerable(void) https://github.com/ruby/ruby/blob/trunk/enum.c#L3780
     rb_define_method(rb_mEnumerable, "slice_after", enum_slice_after, -1);
     rb_define_method(rb_mEnumerable, "slice_when", enum_slice_when, 0);
     rb_define_method(rb_mEnumerable, "chunk_while", enum_chunk_while, 0);
+    rb_define_method(rb_mEnumerable, "sum", enum_sum, -1);
 
     id_next = rb_intern("next");
     id_call = rb_intern("call");
Index: test/ruby/test_hash.rb
===================================================================
--- test/ruby/test_hash.rb	(revision 55031)
+++ test/ruby/test_hash.rb	(revision 55032)
@@ -1415,6 +1415,11 @@ class TestHash < Test::Unit::TestCase https://github.com/ruby/ruby/blob/trunk/test/ruby/test_hash.rb#L1415
     assert_equal([10, 20, 30], [1, 2, 3].map(&h))
   end
 
+  def test_sum
+    histogram = { 1 => 6, 2 => 4, 3 => 3, 4 => 7, 5 => 5, 6 => 4 }
+    assert_equal(100, histogram.sum {|v, n| v * n })
+  end
+
   class TestSubHash < TestHash
     class SubHash < Hash
       def reject(*)
Index: test/ruby/test_range.rb
===================================================================
--- test/ruby/test_range.rb	(revision 55031)
+++ test/ruby/test_range.rb	(revision 55032)
@@ -631,4 +631,9 @@ class TestRange < Test::Unit::TestCase https://github.com/ruby/ruby/blob/trunk/test/ruby/test_range.rb#L631
     end
     (a.."c").each {|x, &b| assert_nil(b)}
   end
+
+  def test_sum
+    assert_equal(55, (1..10).sum)
+    assert_equal(110, (1..10).sum {|v| v * 2 })
+  end
 end
Index: test/ruby/test_enum.rb
===================================================================
--- test/ruby/test_enum.rb	(revision 55031)
+++ test/ruby/test_enum.rb	(revision 55032)
@@ -815,4 +815,94 @@ class TestEnumerable < Test::Unit::TestC https://github.com/ruby/ruby/blob/trunk/test/ruby/test_enum.rb#L815
     assert_equal([[1,2],0,[3,4],1],
                  @obj.each_with_index.flat_map(&lambda2))
   end
+
+  def assert_typed_equal(e, v, cls, msg=nil)
+    assert_kind_of(cls, v, msg)
+    assert_equal(e, v, msg)
+  end
+
+  def assert_int_equal(e, v, msg=nil)
+    assert_typed_equal(e, v, Integer, msg)
+  end
+
+  def assert_rational_equal(e, v, msg=nil)
+    assert_typed_equal(e, v, Rational, msg)
+  end
+
+  def assert_float_equal(e, v, msg=nil)
+    assert_typed_equal(e, v, Float, msg)
+  end
+
+  def assert_complex_equal(e, v, msg=nil)
+    assert_typed_equal(e, v, Complex, msg)
+  end
+
+  def test_sum
+    class << (enum = Object.new)
+      include Enumerable
+      def each
+        yield 3
+        yield 5
+        yield 7
+      end
+    end
+    assert_int_equal(15, enum.sum)
+
+    assert_int_equal(0, [].each.sum)
+    assert_int_equal(3, [3].each.sum)
+    assert_int_equal(8, [3, 5].each.sum)
+    assert_int_equal(15, [3, 5, 7].each.sum)
+    assert_rational_equal(8r, [3, 5r].each.sum)
+    assert_float_equal(15.0, [3, 5, 7.0].each.sum)
+    assert_float_equal(15.0, [3, 5r, 7.0].each.sum)
+    assert_complex_equal(8r + 1i, [3, 5r, 1i].each.sum)
+    assert_complex_equal(15.0 + 1i, [3, 5r, 7.0, 1i].each.sum)
+
+    assert_int_equal(2*FIXNUM_MAX, Array.new(2, FIXNUM_MAX).each.sum)
+    assert_int_equal(2*(FIXNUM_MAX+1), Array.new(2, FIXNUM_MAX+1).each.sum)
+    assert_int_equal(10*FIXNUM_MAX, Array.new(10, FIXNUM_MAX).each.sum)
+    assert_int_equal(0, ([FIXNUM_MAX, 1, -FIXNUM_MAX, -1]*10).each.sum)
+    assert_int_equal(FIXNUM_MAX*10, ([FIXNUM_MAX+1, -1]*10).each.sum)
+    assert_int_equal(2*FIXNUM_MIN, Array.new(2, FIXNUM_MIN).each.sum)
+
+    assert_float_equal(0.0, [].each.sum(0.0))
+    assert_float_equal(3.0, [3].each.sum(0.0))
+    assert_float_equal(3.5, [3].each.sum(0.5))
+    assert_float_equal(8.5, [3.5, 5].each.sum)
+    assert_float_equal(10.5, [2, 8.5].each.sum)
+    assert_float_equal((FIXNUM_MAX+1).to_f, [FIXNUM_MAX, 1, 0.0].each.sum)
+    assert_float_equal((FIXNUM_MAX+1).to_f, [0.0, FIXNUM_MAX+1].each.sum)
+
+    assert_rational_equal(3/2r, [1/2r, 1].each.sum)
+    assert_rational_equal(5/6r, [1/2r, 1/3r].each.sum)
+
+    assert_equal(2.0+3.0i, [2.0, 3.0i].each.sum)
+
+    assert_int_equal(13, [1, 2].each.sum(10))
+    assert_int_equal(16, [1, 2].each.sum(10) {|v| v * 2 })
+
+    yielded = []
+    three = SimpleDelegator.new(3)
+    ary = [1, 2.0, three]
+    assert_float_equal(12.0, ary.each.sum {|x| yielded << x; x * 2 })
+    assert_equal(ary, yielded)
+
+    assert_raise(TypeError) { [Object.new].each.sum }
+
+    large_number = 100000000
+    small_number = 1e-9
+    until (large_number + small_number) == large_number
+      small_number /= 10
+    end
+    assert_float_equal(large_number+(small_number*10), [large_number, *[small_number]*10].each.sum)
+    assert_float_equal(large_number+(small_number*10), [large_number/1r, *[small_number]*10].each.sum)
+    assert_float_equal(large_number+(small_number*11), [small_number, large_number/1r, *[small_number]*10].each.sum)
+
+    assert_equal("abc", ["a", "b", "c"].each.sum(""))
+    assert_equal([1, [2], 3], [[1], [[2]], [3]].each.sum([]))
+
+    assert_separately(%w[-rmathn], <<-EOS, ignore_stderr: true)
+      assert_equal(6, [1r, 2, 3r].each.sum)
+    EOS
+  end
 end

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]