From: Mikael Brockman Date: 2004-07-07T03:15:22+09:00 Subject: Re: Functional Ruby (Re: Why I don't use Ruby.) Joel VanderWerf writes: > Mikael Brockman wrote: >> Joel VanderWerf writes: >> >>>Mikael Brockman wrote: >>> >>>>In Scheme, sum would be: >>>> (define (sum xs) >>>> (if (null? xs) >>>> 0 >>>> (+ (car xs) (sum (cdr xs))))) >>> >>>Ruby doesn't optimize this tail recursion, but Scheme does. That's one >>>way Scheme could be said to be more "functional". >> There's no tail recursion in that function, but you have a point. >> TCO >> would be nice, but it's easy to perform the optimization manually. > > Oops. Quite right. The (+ ...) prevents that. I think sum can be > written in a TCO-friendly way though: call a second function sum2 that > has two args, an accumulator and xs, which recurses with > > (sum2 (+ acc (car xs)) (cdr xs)) > > Anyway, once you've manually optimized a tail call in ruby, it doesn't > look very functional any more, does it? Maybe I'm not understanding > your suggestion... It doesn't _look_ very functional, but it is. The same concepts are embodied in def sum (xs) tally = 0 until xs.empty? tally += xs.first xs = xs.rest end tally end as in (define (sum xs) (sum-acc xs 0)) (define (sum-acc xs acc) (if (empty? xs) acc (sum-acc (cdr xs) (+ (car xs) acc)))). Real programmers can write Scheme in any sufficiently powerful language. It's probably possible in Java, but extremely tedious. Ruby is much better. The notation for closures in Ruby is even _better_ than the lambda of Scheme! mikael