如何将两个过程组合成一个?

时间:2022-05-07 12:19:21

Just wondering if there's a syntax shortcut for taking two procs and joining them so that output of one is passed to the other, equivalent to:

只是想知道是否有一个语法快捷方式,用于获取两个proc并加入它们,以便将一个的输出传递给另一个,相当于:

a = ->(x) { x + 1 }
b = ->(x) { x * 10 }
c = ->(x) { b.( a.( x ) ) }

This would come in handy when working with things like method(:abc).to_proc and :xyz.to_proc

当使用方法(:abc).to_proc和:xyz.to_proc之类的东西时,这会派上用场

3 个解决方案

#1


7  

More sugar, not really recommended in production code

更多的糖,在生产代码中并不是真正推荐的

class Proc
  def *(other)
    ->(*args) { self[*other[*args]] }
  end
end

a = ->(x){x+1}
b = ->(x){x*10}
c = b*a
c.call(1) #=> 20

#2


2  

a = Proc.new { |x| x + 1 }
b = Proc.new { |x| x * 10 }
c = Proc.new { |x| b.call(a.call(x)) }

#3


2  

you could create a union operation like so

你可以像这样创建一个联合操作

class Proc
   def union p
      proc {p.call(self.call)}
   end
end
def bind v
   proc { v}
end

then you can use it like this

然后你可以像这样使用它

 a = -> (x) { x + 1 }
 b = -> (x) { x * 10 }
 c = -> (x) {bind(x).union(a).union(b).call}

#1


7  

More sugar, not really recommended in production code

更多的糖,在生产代码中并不是真正推荐的

class Proc
  def *(other)
    ->(*args) { self[*other[*args]] }
  end
end

a = ->(x){x+1}
b = ->(x){x*10}
c = b*a
c.call(1) #=> 20

#2


2  

a = Proc.new { |x| x + 1 }
b = Proc.new { |x| x * 10 }
c = Proc.new { |x| b.call(a.call(x)) }

#3


2  

you could create a union operation like so

你可以像这样创建一个联合操作

class Proc
   def union p
      proc {p.call(self.call)}
   end
end
def bind v
   proc { v}
end

then you can use it like this

然后你可以像这样使用它

 a = -> (x) { x + 1 }
 b = -> (x) { x * 10 }
 c = -> (x) {bind(x).union(a).union(b).call}