lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On this day of 03/15/2007 05:46 AM, Alex Queiroz saw fit to scribe:
> Hallo,
> 
> On 3/15/07, David Haley <dchaley@gmail.com> wrote:
>
>     Of course you can do recursion in Java, as you can in C, but it's
> useless. Let's see two factorial functions:
> 
> int fact(int n)
> {
>   if(n == 1) {
>      return 1;
>   } else {
>      return n * fact(n-1);
>   }
> }
> 
> (define (fact n)
>   (define (fact-iter n acc)
>      (if (= n 1)
>          acc
>          (fact-iter (- n 1) (* n acc))))
>   (fact-iter n 1))
> 
>     Now try both with n = 1000000, and see which one blows the stack. :-)

Yes, very true; but that's a different issue, is it not? You can still
understand recursion perfectly well, and better yet you get the added
bonus of knowledge about the stack and tail calls if you understand why
the C or Java versions fail for very deep recursion. (And in Java's
case, that is an issue of the JVM, rather than the syntax/semantics of
the Java language.)

Besides, saying recursion is "useless" is a little strong, don't you
think? There are plenty of recursive solutions that are more elegant
than an iterative solution, with the caveat that you can't recurse too
deep -- but very often the allowed depth is quite enough. Nearly all of
the times I blew the stack using recursion were when I messed up the
recursion's base case. :-) Not because the problem inherently needed
such a deep recursion.


Cheers,
- David

P.S. Incidentally, I received my copy of PiL2 a few days ago and am very
happy with it. It has taken the place of PiL1 on my desk, which now
lives on the bookshelf.

Just wanted to say thanks to all involved for the book, and, of course,
Lua in general.


-- 
~David-Haley
http://david.the-haleys.org