Sha256: 2f29492364871645b0d3722c51ce42471a2d8794bf2e2d06dfde8d1dd6ceb8f9
Contents?: true
Size: 1.5 KB
Versions: 7
Compression:
Stored size: 1.5 KB
Contents
class Proc # Returns a new proc that is the functional # composition of two procs, in order. # # a = lambda { |x| x + 4 } # b = lambda { |y| y / 2 } # # a.compose(b).call(4) #=> 6 # b.compose(a).call(4) #=> 4 # # CREDIT Dave def compose(g) raise ArgumentError, "arity count mismatch" unless arity == g.arity lambda{ |*a| self[ *g[*a] ] } end # Operator for Proc#compose and Integer#times_collect/of. # # a = lambda { |x| x + 4 } # b = lambda { |y| y / 2 } # # (a * b).call(4) #=> 6 # (b * a).call(4) #=> 4 # # CREDIT Dave def *(x) if Integer===x # collect times a = []; x.times{|i| a << call(i)}; a else # compose procs lambda{|*a| self[x[*a]]} end end # Use a Proc as an observable. # # CREDIT Tim Pease alias_method :update, :call end # _____ _ # |_ _|__ ___| |_ # | |/ _ \/ __| __| # | | __/\__ \ |_ # |_|\___||___/\__| # =begin test require 'test/unit' class TestProc < Test::Unit::TestCase def test_compose_op a = lambda { |x| x + 4 } b = lambda { |y| y / 2 } assert_equal( 6, (a * b).call(4) ) assert_equal( 4, (b * a).call(4) ) end def test_times_collect_op a = lambda { |x| x + 4 } assert_equal( [4,5,6], a * 3 ) end def test_compose a = lambda { |x| x + 4 } b = lambda { |y| y / 2 } assert_equal( 6, (a.compose(b)).call(4) ) assert_equal( 4, (b.compose(a)).call(4) ) end end =end
Version data entries
7 entries across 7 versions & 1 rubygems