From: Luigi Ballabio Date: 2001-03-16T17:53:59+09:00 Subject: [ruby-talk:12734] Re: Sum of Squares At 02:14 AM 3/16/01 +0900, you wrote: >On Tue, 13 Mar 2001, rashworth wrote: > > Thank you for your note. The new coding worked just fine. > > Do you have some code for the Sum of the Cross-Products? > > Sumxy = (x1 * y1) + (x2 * y2) + .... > >That is called a dot product, not a "sum of cross-products". Unfortunately >you can't run two iterators at once easily, but you can still write: > >class Array > def dot(other) > # other.type == Array > # other.length == self.length > sum = 0 > length.times {|i| sum += self[i]*other[i] } > sum > end >end To follow up on the Haskell-functional programming thing, this is where [1,2,3].zip([4,5,6]) # --> [[1,4],[2,5],[3,6]] and [1,2,3].inject(0) { |a,b| a+b } # --> 1+2+3 = 6 could come handy - the above would be class Array def dot(other) self.zip(other).map { |a| a[0]*a[1] } .inject(0) { |a,b| a+b } end end Bye, Luigi