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.
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 |
# File 'lib/coroutines.rb', line 290 def <=(source) if source.respond_to? :each LazyEnumerator.new(source) do |y, *args| value = call(*args) y << value unless value.nil? end 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.
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 |
# File 'lib/coroutines.rb', line 317 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, "
275 276 277 278 279 280 281 282 |
# File 'lib/coroutines.rb', line 275 def to_trans Transformer.new do |y| loop do value = self.call(y.await) y.yield value unless value.nil? end end end |