From: Ned Konz Date: 2002-06-07T00:13:33+09:00 Subject: Re: Array.foldr (Array.reduce) On Thursday 06 June 2002 07:55 am, Kontra, Gergely wrote: > folr e + array = array1 + (array2 + ... + (arrayn + e)...) > > > And foldl is the other way (if + is associative, then it gives the > same result) > > > If inject will be available, will foldl and foldr (=reduce) also? > Thanks in advance. If I understand you, you could just do this: # used like: # foldr(e, array) { |partial,b| partial+b } def foldr(e, array) result = e array.reverse_each { |elem| result = yield(result, elem) } result end # Same thing, but left associative def foldl(e, array) result = e array.each { |elem| result = yield(result, elem) } result end # and you should provide it for Enumerables too: module Enumerable def foldr(e) result = e reverse_each { |elem| result = yield(result, elem) } result end # Same thing, but left associative def foldl(e) result = e each { |elem| result = yield(result, elem) } result end end arr = [1,2,3,4,5] p foldr(6, arr) { |a,b| a + b } => 21 p arr.foldr(6) { |a,b| a + b } => 21 -- Ned Konz http://bike-nomad.com GPG key ID: BEEA7EFE