From: rashworth Date: 2001-03-17T13:22:06+09:00 Subject: [ruby-talk:12760] Re: Sum of Squares thanks for your code. ERA ---------- Original Message ---------------------------------- From: Luigi Ballabio Reply-To: ruby-talk@ruby-lang.org Date: Fri, 16 Mar 2001 17:53:59 +0900 >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 > >