Why you should explicitly specify two arguments for curry:>

Consider this, which works great:

:>.to_proc.curry(2)[9][8] #=> true, because 9 > 8

However, although it >is a binary operator, the above will not work without the specified arity:

:>.to_proc.curry[9][8] #=> ArgumentError: wrong number of arguments (0 for 1)

Why not two equivalents?

Note. I specifically want to create an intermediate currency function with one argument included, and then call it then call it with the second argument.

+4
source share
3 answers

Curry should know how far the arch went by, right?

 :<.to_proc.arity  # => -1

Negative values ​​from arityare confusing, but basically mean "a variable number of arguments" anyway.

Compare with:

 less_than = lambda {|a, b| a < b}
 less_than.arity # => 2

-, , , #curry.

 less_than.curry[9][8] # => false, no problem!

#to_proc , , , , . , < ruby, , , , # to_proc - , , args , proc .

C , MRI, , # to_proc proc . # to_proc, , . , , , :

hello_proc = :hello.to_proc
class SomeClass
  def hello(name = nil)
     puts "Hello, #{name}!"
  end
end
obj = SomeClass.new
obj.hello #=> "Hello, !"
obj.hello("jrochkind") #=> "Hello, jrochkind!"
obj.hello("jrochkind", "another")
# => ArgumentError: wrong number of arguments calling `hello` (2 for 1)

hello_proc.call(obj)  # => "Hello, !"
hello_proc.call(obj, "jrochkind") # => "Hello, jrochkind!"
hello_proc.call(obj, "jrochkind", "another")
# => ArgumentError: wrong number of arguments calling `hello` (2 for 1)

hello_proc.call("Some string")
# => NoMethodError: undefined method `hello' for "Some string":String

. hello_proc = :hello.to_proc, SomeClass. Symbol # to_proc arity proc, , , proc, , .

C, :

class Symbol
  def to_proc
    method_name = self
    proc {|receiver, *other_args|  receiver.send(method_name, *other_args) }
  end
end
+4

, , Symbol#to_proc proc . proc, :> :

->x, y{...}

:

->x{...}

>, - proc ( , > , , , ). ,

:>.to_proc.arity # => -1
->x, y{}.arity # => 2

, curry ; proc . 2, - . join:

:join.to_proc.arity # => -1
:join.to_proc.call(["x", "y"]) # => "xy"
:join.to_proc.curry.call(["x", "y"]) # => "xy"

, Currying :join .

+2

@jrochkind , :>.to_proc.curry . , :

, .

Object#method. :

nine_is_greater_than = :>.to_proc.curry[9]
nine_is_greater_than[8]
#=> ArgumentError: wrong number of arguments (0 for 1)

... :

nine_is_greater_than = 9.method(:>)
nine_is_greater_than[8]
# => true

Object#method Method, Proc: call, [], ( Ruby 2.2) curry. , proc ( curry Ruby < 2.2), to_proc ( &, to_proc):

[ 1, 4, 8, 10, 20, 30 ].map(&nine_is_greater_than)
# => [ true, true, true, false, false, false ]
+2

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


All Articles