From: Louis J Scoras Date: 2005-10-20T06:06:37+09:00 Subject: Re: Functional with Ruby ------=_Part_1759_17736303.1129755995276 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline On 10/19/05, Florian Frank wrote: > > > I think the point is, that you can use foldr, a function that is defined > in Haskell only in terms of recursion. But Ruby's inject isn't defined > in Ruby, it's a method of Array (a stateful data structure) written in C > and it is actually implemented iterative. The Ruby version isn't really > functional, it's only very similar, while the Haskell foldr is a > recursivley defined function. So if you want to play with functional > style programming in Ruby, using Array#inject is a bit fishy. > > On the other hand, if you want to write a reasonable fast program in > Ruby, I would avoid recursion as much as possible, go for iteration, and > concentrate on using methods implemented in C instead. But it seemed to > me, that the OP was more interested in learning about functional > programming (using Ruby as well as Haskell), than writing fast programs. Hehe. You got me there. How about this then? class Array def fold(start =3D nil, &block) start =3D self[0] unless start return start if self.length =3D=3D 0 yield(self[1..-1].fold(start, &block), self[0]) end def my_sum; fold {|total, i| total + i} ; end def my_length; fold(0) {|length, i| length + 1} ; end def my_to_s; fold('') {|buffer, i| buffer << i.to_s }.reverse ; end end x =3D [1,3,5,2,3] puts x.my_sum puts x.my_length puts x.my_to_s Or is the problem that there are method calls at all? Isn't Haskell defined in C? Eventually at some level you're going to have to maintain state. We have C because of good old Von Neumann. Again, I'm very rusty, but doesn't this boil down to not having side-effects? Is inject referentially transparent if you consider the reciever to be an implicit parameter? -- Lou ------=_Part_1759_17736303.1129755995276--