compose(*)函数如何在Ruby中工作(来自Ruby编程语言)?

Dan*_*son 3 ruby functional-programming

摘录Ruby编程语言:

module Functional
  def compose(f)
    if self.respond_to?(:arity) && self.arity == 1
      lambda {|*args| self[f[*args]] }
    else
      lambda {|*args| self[*f[*args]] }
    end
  end
  alias * compose
end

class Proc; include Functional; end
class Method; include Functional; end

f = lambda {|x| x * 2 }
g = lambda {|x, y| x * y}
(f*g)[2, 3] # => 12
Run Code Online (Sandbox Code Playgroud)

if/else子句中f和*f有什么区别?

7st*_*tud 5

*任一收集的所有项目到一个数组,或爆炸的阵列成单独的元件-这取决于上下文.

如果args = [1, 2, 3],那么:

  • f[args] 相当于 f[ [1, 2, 3] ] #There is one argument: an array.
  • f[*args] 相当于 f[1, 2, 3] #There are three arguments.

如果f[*args]返回[4, 5, 6],则:

  • self[f[*args]] 相当于 self[ [4, 5, 6] ] #self is called with 1 arg.
  • self[*f[*args]] 相当于 self[4, 5, 6] #self is called with 3 args.

*用于将项目收集到Array中的示例是:

  • lambda {|*args| ....}

您可以使用任意数量的参数调用该函数,并将所有参数收集到一个数组中并分配给参数变量args.