Friday, November 26, 2010

Currying in Ruby

I've spent the last month playing around with ruby, mostly because I feel I should. I'd like to share with you some cool things you can do with functions in Ruby 1.9. I discovered this by starting with a question.

In python, you could do this sort of thing.

def foo():
    return "bar"

x = foo

print x() # "bar"

In ruby you can call a function without brackets. So you can do:

def foo()
    return "bar"
end

puts foo # "bar"

My question was. How would you pass a function in ruby? This is one way:

def foo()
    return "foo"
end

x = lambda {foo}
puts x
puts x.call() # "foo"

Starting from humble beginnings. I wondered if I could use this mechanism for setting up a function with arguments that I could call later. The way you do this is quite intuitive.

def add(a,b)
    return a+b
end

y = lambda{add(3,2)}
puts y
puts y.call() # 5

From here its easy to think that currying in ruby must be very simple. It is!

def add(a,b)
    return a+b
end

plus = lambda {|a,b| add(a,b)}
curry_plus = plus.curry
plus_two = curry_plus[2]
puts plus_two[3] # 5

No comments:

Post a Comment