Ruby 中的简单柯里化
我正在尝试在 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]
收到错误
func_test.rb:24:in `[]': wrong number of arguments (1 for 0) (ArgumentError)
我从 func_test.rb:24:in `'
,但如果我这样做,
plus = lambda {|a,b| a+ b}
它似乎可以工作。但是通过在 lambda 赋值后打印 plus,两种方法都会返回相同类型的对象。我误解了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您走在正确的道路上:
正如其他人所指出的,您定义的
plus
lambda 不接受任何参数,并且调用不带参数的add
方法。You're on the right track:
As others have pointed out, the
plus
lambda you defined doesn't take any arguments and calls theadd
method with no arguments.创建一个 lambda,它接受两个参数并返回对第一个参数调用
+
的结果,第二个参数作为其参数。创建一个不带参数的 lambda,并在不带参数的情况下调用
add
,这当然是一个错误。为了做你想做的事,你应该做
或者
Creates a lambda which takes two arguments and returns the result of calling
+
on the first, with the second as its arguments.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
or
当您编写
lambda {add}
时,您声明了一个不带参数的Proc,并且作为其唯一操作,调用不带参数的add
。它不会将add
转换为 Proc。另一方面,lambda {|a,b| a + b} 返回一个 Proc,它接受两个参数并将它们加在一起 - 因为它接受参数,所以将参数传递给该参数是有效的。我认为你想要的是
method(:add).to_proc.curry
。When you write
lambda {add}
, you're declaring a Proc that takes no arguments and, as its sole action, callsadd
with no arguments. It doesn't turnadd
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
.