From: Pixel Date: 2000-02-15T02:26:06+01:00 Subject: [ruby-talk:01355] nice sample for functional stuff what about having map in standard (and map_index too)? sorry to bother you... but bash me for any bad style... -------------------------------------------------------------------------------- class Array def map dup.filter{|i| yield(i) } end def map_index l = [] each_index{|i| l += yield(i, self[i]) } l end def fold_left a = self[0] self[1..-1].each{|i| a = yield(a, i) } a end def sum; fold_left{|i,j| i+j}; end end def fold_left(f, *l) a = l.shift l.each{|i| a = f.call(a, i) } a end def sum1(*l); fold_left(proc{|i,j| i+j }, *l); end def fold_left2(*l) a = l.shift l.each{|i| a = yield(a, i) } a end # is same as def fold_left2(*l, &f) a = l.shift l.each{|i| a = f.call(a, i) } a end def sum2(*l); fold_left2(*l){|i,j| i+j }; end def sum3(*l); l.fold_left{|i,j| i+j}; end p sum1(1, 2, 3) p sum2(1, 2, 3) p sum3(1, 2, 3) p [1, 2, 3].sum def mapn(*l) l[0].map_index{|i,_e| yield(l.map{|e| e[i]}) } end def zip(*l); mapn(*l){|l| [l]}; end def unzip(l); mapn(*l){|l| [l]}; end p l = zip(a = [1,2,10], b = [1,2,222]) (a2,b2) = unzip(l) p a==a2, b==b2 --------------------------------------------------------------------------------