From: Florian Frank Date: 2005-10-20T07:08:57+09:00 Subject: Re: Functional with Ruby Robert Klemme wrote: > 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. You're right. And I knew that. ;) > 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. If you wanted to define the type signature of inject, it would be quite difficult. You cannot omit the start value in Haskell foldr, for example. Ruby takes a rather pragmatic approach to typing, while Haskell has a much more pedantic one. >> 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: Yeah. I once made a quicksort in one lambda, when I was bored: quicksort = lambda do |a| if x = a[0] l, r = lambda do |b, p| t, f = [], [] for z in b do if p[z] then t << z else f << z end end [ t, f ] end[ a[1..-1], lambda { |y| y <= x } ] quicksort[l] + [ x ] + quicksort[r] else [] end end p quicksort[ [5,3,8,1,4,9,7,2,10,6] ] There are still Array operations used, but you could as well define cons pairs in terms of lambda, and then define lists of them. You could define a Y combinator to get rid of the quicksort assignment for the recursion, and so on. For learning and having fun this is great, but I guess it will get rather slow and be a memory hog, if you expect that to do real work. -- Florian Frank