How to create lambda from lambda with parameter without executing .call in Ruby?

I want to create a new lambda with no arguments from the lambda taking it.

Say I have

irb(main):001:0> f1 = lambda { |p| p } => #<Proc: 0x00000001045190@ (irb):1 (lambda)> irb(main):002:0> f1.call(2) => 2 

and now I

 irb(main):003:0> f2 = lambda { f1.call(2) } => #<Proc: 0x00000000f620e8@ (irb):3 (lambda)> irb(main):004:0> f2.call => 2 

but I do not want to create a lambda around the first, but I want to "substitute" a parameter for it or something like that.

Maybe if we have a call , there is some kind of magic that does the same thing as the call, but returns a lambda, except for the actual code call:

 f2 = f1.some_magic(2) f2.call => 2 

PS Sorry, if this question is dumb, this functional material is difficult for me to understand sometimes.

PPS Found this section on ruby-forum.com, and it seems I want to do the same without any extra overhead.

+4
source share
2 answers

You can create a function that binds arguments to proc. This works with Ruby> = 1.8:

 def bind_args(l, *bound_args) lambda { |*unbound_args| l[*(bound_args + unbound_args)] } end 

Using:

 f1 = lambda { |p| p } f2 = bind_args(f1, 2) p f2.call # 2 

If you want to bind some, but not all, arguments, you can also do this:

 f1 = lambda { |p, q| [p, q] } f2 = bind_args(f1, 2) p f2.call(3) # [2, 3] 

Except curry makes a call, not a new lambda, if full lambda binding arguments are given, this is pretty much what curry does. I did not call it curry to avoid confusion with the method of this name built into Ruby 1.9.

+3
source

Are you looking for curry ?:

 f1 = lambda { |p| p } p f1.curry[2] #=> 2 

Curry is available in Ruby 1.9

+3
source

Source: https://habr.com/ru/post/1389368/


All Articles