Class: Proc
Instance Method Summary collapse
-
#<=(source) ⇒ Object
:call-seq: proc <= trans -> new_trans proc <= enum -> new_enum.
-
#>=(sink) ⇒ Object
:call-seq: proc >= trans -> new_trans proc >= sink -> new_consumer.
-
#to_trans ⇒ Object
:call-seq: proc.to_trans -> transformer.
Instance Method Details
#<=(source) ⇒ Object
:call-seq:
proc <= trans -> new_trans
proc <= enum -> new_enum
Equivalent to proc.to_trans <= trans/enum, except that it uses a more efficient implementation.
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 |
# 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 |
#>=(sink) ⇒ Object
:call-seq:
proc >= trans -> new_trans
proc >= sink -> new_consumer
Equivalent to proc.to_trans >= trans/sink, except that it uses a more efficient implementation.
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 |
# 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 ⇒ Object
:call-seq:
proc.to_trans -> transformer
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, "
119 120 121 122 123 124 125 126 |
# 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 |