Sha256: 14911a1532f2161766e37a92e50ced3a8ffdef202a0c55c814aa0c322397c40d

Contents?: true

Size: 1.17 KB

Versions: 16

Compression:

Stored size: 1.17 KB

Contents

#--
# Thanks dave!
#++
class Proc

  # Returns a new proc that is the functional
  # compostion of two procs, in order.
  #
  #  a = lambda { |x| x + 4 }
  #  b = lambda { |y| y / 2 }
  #
  #  a.compose(b).call(4)  #=> 6
  #  b.compase(a).call(4)  #=> 4
  #
  def compose(other)
    raise ArgumentError, "arity count mismatch" unless arity == other.arity
    #proc{ |*a| self.call(other.call(*a)) }
    proc{ |*a| self.call(*other.call(*a)) }
  end

  # Operator for compose.
  #
  #  a = lambda { |x| x + 4 }
  #  b = lambda { |y| y / 2 }
  #
  #  (a * b).call(4)  #=> 6
  #  (b * a).call(4)  #=> 4
  #
  alias_method( :*, :compose )

end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCProc < Test::Unit::TestCase

    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

    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

  end

=end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
facets-1.0.0 lib/facet/proc/compose.rb
facets-0.9.0 lib/nano/proc/compose.rb
facets-1.0.3 packages/core/lib/facet/proc/compose.rb
facets-1.2.1 lib/facets/core/proc/compose.rb
facets-1.2.0 lib/facets/core/proc/compose.rb
facets-1.3.0 lib/facets/core/proc/compose.rb
facets-1.1.0 lib/facet/proc/compose.rb
facets-1.3.1 lib/facets/core/proc/compose.rb
facets-1.3.3 lib/facets/core/proc/compose.rb
facets-1.3.2 lib/facets/core/proc/compose.rb
facets-1.4.1 lib/facets/core/proc/compose.rb
facets-1.4.2 lib/facets/core/proc/compose.rb
facets-1.4.0 lib/facets/core/proc/compose.rb
facets-1.4.3 lib/facets/core/proc/compose.rb
facets-1.4.4 lib/facets/core/proc/compose.rb
facets-1.4.5 lib/facets/core/proc/compose.rb