class Proc

Public Instance Methods

proc <= trans → new_trans click to toggle source
proc <= enum → new_enum

Equivalent to proc.to_trans <= trans/enum, except that it uses a more efficient implementation.

# File lib/coroutines/operators.rb, line 134
def <=(source)
        if source.respond_to? :each
                Enumerator.new do |y|
                        source.each do |obj|
                                value = call obj
                                y << value unless value.nil?
                        end
                end.lazy
        elsif source.respond_to? :to_proc
                sp = source.to_proc
                proc do |*args|
                        value = sp.call(*args)
                        if value.nil? then nil else self.call value end
                end
        elsif source.respond_to? :to_trans
                # FIXME: this could be implemented more efficiently; proc doesn't
                #        need to run in a separate Fiber
                self.to_trans <= source.to_trans
        else
                raise ArgumentError, "#{source.inspect} is neither an enumerable nor a transformer"
        end
end
proc >= trans → new_trans click to toggle source
proc >= sink → new_consumer

Equivalent to proc.to_trans >= trans/sink, except that it uses a more efficient implementation.

# File lib/coroutines/operators.rb, line 163
def >=(sink)
        if sink.respond_to? :input_map
                sink.input_reject(&:nil?).input_map(&self)
        elsif sink.respond_to? :to_proc
                sp = sink.to_proc
                proc do |*args|
                        value = self.call(*args)
                        if value.nil? then nil else sp.call value end
                end
        elsif sink.respond_to? :to_trans
                # FIXME: this could be implemented more efficiently; proc doesn't
                #        need to run in a separate Fiber
                self.to_trans >= sink.to_trans
        else
                raise ArgumentError, "#{sink.inspect} is neither a sink nor a transformer"
        end
end
to_trans → transformer click to toggle source

Allows implicit conversion of Proc to Transformer. The transformer is a combination of map and filter over its input values: For each input value, proc is called with the input value as parameter. Every non-nil value returned by proc is yielded as an output value.

This is similar to Enumerable#map followed by Array#compact, but without constructing the intermediate Array (so it's even more similar to something like enum.lazy.map(&proc).reject(&:nil?), using the lazy enumerator introduced in Ruby 2.0).

Example:

(1..10) >= proc{|x| x.to_s + ", " if x.even? } >= ""
# => "2, 4, 6, 8, 10, "
# File lib/coroutines/operators.rb, line 119
def to_trans
        Transformer.new do |y|
                loop do
                        value = self.call(y.await)
                        y.yield value unless value.nil?
                end
        end
end