Method: Enumerable#ewise
- Defined in:
- lib/core/facets/enumerable/ewise.rb
#ewise(count = 1) ⇒ Object Also known as: elementwise
Returns an elementwise Functor designed to make R-like elementwise operations possible. This is very much like the #every method, but it treats array argument specially.
([1,2].ewise + 3) #=> [4,5]
Vector to vector
([1,2].ewise + [4,5]) #=> [5,7]
Special thanks to Martin DeMello for helping to develop this.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/core/facets/enumerable/ewise.rb', line 19 def ewise(count=1) Functor.new do |op,*args| if args.empty? r = self count.times do r = r.collect{ |a| a.send(op) } end r else r = args.collect do |arg| if Array === arg #arg.kind_of?(Enumerable) x = self count.times do ln = (arg.length > length ? length : arg.length ) x = x.slice(0...ln) x = x.zip(arg[0...ln]) x = x.collect{ |a,b| a.send(op,b) } #x = x.collect{ |a,b| b ? a.send(op,b) : nil } end x else x = self count.times do x = x.collect{ |a| a.send(op,arg) } end x end end r.flatten! if args.length == 1 r end end end |