Ruby Snippet: Function Composition

# (map (comp - *) [2 4 6] [1 2 3])

class Proc
  def comp f, g
    ->(*args){f.call(g.call(*args))}
  end

  def * g
    comp(self, g)
  end
end

multiply  = ->(x, y){x * y}
negative  = ->(x){-x}
composed  = negative * multiply

composed.call(9,9)                                    # => -81

[2,4,6].zip([1,2,3]).map{|x, y| composed.call(x, y)}  # => [-2, -8, -18]
This entry was posted in News. Bookmark the permalink.

Comments are closed.