Sha256: de89b5d97e04ec68a35ed7d896090ea7ad976483b9245636e879a670fdce0c14

Contents?: true

Size: 788 Bytes

Versions: 2

Compression:

Stored size: 788 Bytes

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
      c = []
      x.times{|i| c << call(i)}
      c
    else
      # compose procs
      lambda{|*a| self[x[*a]]}
    end
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
facets-2.2.1 lib/core/facets/proc/compose.rb
facets-2.3.0 lib/core/facets/proc/compose.rb