From: Robert Klemme Date: 2005-10-20T06:11:59+09:00 Subject: Re: Functional with Ruby Florian Frank wrote: > Louis J Scoras wrote: > >> Yes, it is ultimately defined recursively, but the complexity is >> pushed down into the fold* functions. Granted it's a pretty simple >> recursion, but the point still holds. >> >> > 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. AFAIK it's implemented in module Enumerable but apart from that you're right. Even if it was implemented in Ruby it would be implemented in terms of #each and thus iteratively. >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. Well, yes. Interestingly if you view a block as an anonymous function (which is what it is basically) Enumerable#inject has the same interface (apart from syntax) as foldr. Arguments are an initialization value and a binary function. > 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. Definitely. > 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. You could do something like this, but it still feels awkward - Ruby is mainly OO and not functional. Still, it can be done: >> foldr = lambda do |enum, start, fun| ?> enum.each {|x| start = fun[start,x]} >> start >> end => # >> add = lambda {|a,b| a+b} => # >> a=[1,2,3,4,5,6] => [1, 2, 3, 4, 5, 6] >> foldr[ a, 0, add ] => 21 >> foldr[ 1..6, 0, add ] => 21 Kind regards robert