lua-users home
lua-l archive

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


Alex Queiroz 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. :-)

Alex, that is comparing apples and oranges. The first example is true
recursion, the second is iteration. SICP (Structure and Interpretation
of Computer Programs) makes this distinction very early on. If your
point is that C does not provide support for tail recursion, say so. The
proper Scheme example would be:

guile> (define (fact n) (if (= n 1) 1 (* n (fact (- n 1)))))
guile> (fact 12)
479001600
guile> (fact 100000)
ERROR: Stack overflow
ABORT: (stack-overflow)
guile>

Doug


-- 
Innovative Concepts, Inc. www.innocon.com 703-893-2007 x220