Project

General

Profile

Feature #6284 ยป 0002-proc.c-Implement-Method-for-Method-composition.patch

mudge (Paul Mucur), 12/30/2015 12:28 PM

View differences:

proc.c
2871 2871
    return proc;
2872 2872
}
2873 2873

  
2874
 /*
2875
  *  call-seq:
2876
  *     meth * g -> a_proc
2877
  *
2878
  *  Returns a proc that is the composition of this method and the given proc <i>g</i>.
2879
  *  The returned proc takes a variable number of arguments, calls <i>g</i> with them
2880
  *  then calls this method with the result.
2881
  *
2882
  *     def f(x)
2883
  *       x * 2
2884
  *     end
2885
  *
2886
  *     f = self.method(:f)
2887
  *     g = proc {|x, y| x + y }
2888
  *     h = f * g
2889
  *     p h.call(1, 2) #=> 6
2890
  */
2891
static VALUE
2892
rb_method_compose(VALUE self, VALUE g)
2893
{
2894
    VALUE proc = method_to_proc(self);
2895
    return proc_compose(proc, g);
2896
}
2897

  
2874 2898
/*
2875 2899
 *  Document-class: LocalJumpError
2876 2900
 *
......
2985 3009
    rb_define_method(rb_cMethod, "clone", method_clone, 0);
2986 3010
    rb_define_method(rb_cMethod, "call", rb_method_call, -1);
2987 3011
    rb_define_method(rb_cMethod, "curry", rb_method_curry, -1);
3012
    rb_define_method(rb_cMethod, "*", rb_method_compose, 1);
2988 3013
    rb_define_method(rb_cMethod, "[]", rb_method_call, -1);
2989 3014
    rb_define_method(rb_cMethod, "arity", method_arity_m, 0);
2990 3015
    rb_define_method(rb_cMethod, "inspect", method_inspect, 0);
test/ruby/test_method.rb
953 953
    assert_equal('1', obj.foo(1))
954 954
    assert_equal('1', obj.bar(1))
955 955
  end
956

  
957
  def test_compose_with_method
958
    c = Class.new {
959
      def f(x) x * 2 end
960
      def g(x) x + 1 end
961
    }
962
    f = c.new.method(:f)
963
    g = c.new.method(:g)
964
    h = f * g
965

  
966
    assert_equal(6, h.call(2))
967
  end
968

  
969
  def test_compose_with_proc
970
    c = Class.new {
971
      def f(x) x * 2 end
972
    }
973
    f = c.new.method(:f)
974
    g = proc{|x| x + 1}
975
    h = f * g
976

  
977
    assert_equal(6, h.call(2))
978
  end
979

  
980
  def test_compose_with_nonproc_or_method
981
    c = Class.new {
982
      def f(x) x * 2 end
983
    }
984
    f = c.new.method(:f)
985

  
986
    assert_raise(TypeError) {
987
      f * 5
988
    }
989
  end
956 990
end
957
-