繁体   English   中英

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

[英]How does the compose (*) function work in Ruby (from The Ruby Programming Language)?

摘录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

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

*要么将所有项目收集到一个数组中,要么将数组分解为单个元素 - 具体取决于上下文。

如果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.

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

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

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

* (也称为splat)允许您使用参数数组调用方法,而不是单独传递值。 如果你离开了splat,那么ruby只会传递一个值(恰好是一个数组)。 这个一元*不是此代码定义为compose别名的*操作

在if分支中, self的arity为1,则f应返回单个值,因此不需要splat。

在else分支中, self需要多个参数,因此f应该返回一个值数组,而splat用于使用这些参数调用self

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM