13

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?

3 Answers 3

18

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.

Sign up to request clarification or add additional context in comments.

Comments

10
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 

1 Comment

:add.to_proc will not work right. It returns a Proc equivalent to proc {|receiver, *args| receiver.add(*args)}. Which means that :add.to_proc[1,2] will try to call 1.add(2) rather than self.add(1,2).
4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.