Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need to implement Haskell's flip for Proc

Haskell's Prelude has a useful function that swaps a function's arguments: http://zvon.org/other/haskell/Outputprelude/flip_f.html

I need to do the same in Ruby. Instead of just defining a custom method, I would like to monkey patch the Proc class so that I could use flip alongside Proc#curry. Something like

f = lambda {|x, y| [x, y]}
g = f.flip.curry.(2)

to supply a value for y.

I do not know how to reopen Proc class to do that.

like image 617
akonsu Avatar asked Dec 20 '12 20:12

akonsu


1 Answers

class Proc
  def flip
    lambda { |x, y| self.(y, x) }
  end
end


f = lambda { |x, y| [x, y] }
f.flip.(1, 2)
#=> [2, 1]
like image 171
tokland Avatar answered Oct 08 '22 20:10

tokland