From: Robert Klemme Date: 2003-07-23T21:04:20+09:00 Subject: Re: A different Version of Enumerable#inject "Mauricio Fern�ndez" schrieb im Newsbeitrag news:20030723093107.GA14554@student.ei.uni-stuttgart.de... > On Wed, Jul 23, 2003 at 06:03:08PM +0900, Robert Klemme wrote: > > > > Apparently the other post got overlooked - and it had an error in the > > implementation. What do others think of this suggestion of a changed > > Enumerable#inject that uses a sliding window whose size is determined by > > the block's arity. > > I tend to dislike #inject cause it's almost always more complex than > using #each + the needed logic (and slower too), I could agree with the performance issue, although I'd like to test that. But I don't see the difference in complexity between: m = [] enum.each{ |x| m << (m[-1]||0) + x } and m = enum.inject([]) {|m,x| m << (m[-1]||0) + x} In fact, the formula is pretty much the same. :-) > as it's providing the > wrong sort of abstraction in many cases (gets further away from the > problem domain, not closer, IMHO). Hm, that I don't understand. IMHO this follows the spirit of Ruby since it allows to implement a lot of useful things very easily. Could you elaborate or do you have any sources to back that up? > To put it another way, #inject > represents a movement orthogonal to the "complexity line of force". May the force be with you. > However, your extended #inject seems OK to me, because of the sliding > window concept. Now *that* is something useful in some cases, and using > your #inject means I don't have to propagate values. Yep. > I would like it to become common, as it's probably the only kind of > #inject I would like to use :-) :-) > > # integration > > enum.inject([]) {|m,x,y|m<<(x+y).to_f/2} > > Is this really integrating? It won't give the same results as > m = [] > enum.each{ |x| m << (m[-1]||0) + x } > > will it? You're right. That was not the mathematical correct formulation. It's more like an averaging functionality. This should give the same results as yours: enum.inject([0]) {|m,x|m< If I understand what your #inject does, this is only averaging > pair-wise. > (too lazy to read your code now :-) Yep, true. > > # weighted integration > > enum.inject([]) {|m,x,y,z|m<<(x+y+y+z).to_f/4} > > you mean a convolution with [0.25, 0.5, 0.25], no? If "convolution" is the right term. I'm not so used to english statistical terms. > Convolution probably deserves a method on its own, but I don't think > Enumerable#convolution is going to be really used anyway :-) Possibly. Apart from that, Enumerable#convolution might be implemented differently. Thanks for checking robert