Question
I'm trying to do some currying in ruby:
def add(a,b)
return a+b
end
plus = lambda {add}
curry_plus = plus.curry
plus_two = curry_plus[2] #Line 24
puts plus_two[3]
I get the error
func_test.rb:24:in `[]': wrong number of arguments (1 for 0) (ArgumentError)
from func_test.rb:24:in `'
But if I do
plus = lambda {|a,b| a+ b}
It seems to work. But by printing plus after the assigning with lambda both ways return the same type of object. What have I misunderstood?
Solution
lambda {|a,b| a+ b}
Creates a lambda which takes two arguments and returns the result of calling +
on the first, with the second as its arguments.
lambda {add}
Creates a lambda which takes no arguments and calls add
without arguments, which is an error of course.
To do what you want, you should do
plus = lambda {|x,y| add(x,y)}
or
plus = method(:add).to_proc
OTHER TIPS
You're on the right track:
add = ->(a, b) { a + b }
plus_two = add.curry[2]
plus_two[4]
#> 6
plus_two[5]
#> 7
As others have pointed out, the plus
lambda you defined doesn't take any arguments and calls the add
method with no arguments.
When you write lambda {add}
, you're declaring a Proc that takes no arguments and, as its sole action, calls add
with no arguments. It doesn't turn add
into a Proc. On the other hand, lambda {|a,b| a + b}
returns a Proc that takes two arguments and adds them together — since it takes arguments, it's valid to pass arguments to that one.
I think what you want is method(:add).to_proc.curry
.