Ruby 中的简单柯里化

发布于 2024-10-04 15:41:51 字数 466 浏览 1 评论 0原文

我正在尝试在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

伏妖词 2024-10-11 15:41:51

您走在正确的道路上:

add = ->(a, b) { a + b }
plus_two = add.curry[2]
plus_two[4]
#> 6
plus_two[5]
#> 7

正如其他人所指出的,您定义的 plus lambda 不接受任何参数,并且调用不带参数的 add 方法。

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.

贪恋 2024-10-11 15:41:51
lambda {|a,b| a+ b}

创建一个 lambda,它接受两个参数并返回对第一个参数调用 + 的结果,第二个参数作为其参数。

lambda {add}

创建一个不带参数的 lambda,并在不带参数的情况下调用 add,这当然是一个错误。

为了做你想做的事,你应该做

plus = lambda {|x,y| add(x,y)}

或者

plus = method(:add).to_proc
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
神爱温柔 2024-10-11 15:41:51

当您编写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, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文