Java is unable to do tail-call optimisation (TCO), so in Java all recursive 
functions are stack-consuming. Other languages, e.g. Haskell and Scheme, are 
able to do automatic TCO and so tail recursive functions are not 
stack-consuming.

It is not just Java that is unable to perform automatic TCO: As Stuart Halloway 
says in 'Programming Clojure', "no language that runs directly on the JVM can 
perform automatic TCO".

While Clojure (which runs on the JVM) is not able to do automatic TCO, id does 
support TCO: In Clojure you can explicitly tell the compiler that a function is 
tail-recursive by replacing the name of the function in the tail-recursive call 
with the 'recur' keyword.

Here is an example of a tail recursive Fibonacci function

(defn recur-fibo [n]
    (letfn [(fib
                [current next n]
                (if (zero? n)
                    current
                    (recur next (+ current next) (dec n))))]
        (fib 0 1 n)))

The recur-fibo will not consume stack as it calculates Fibonacci numbers, and 
can calculate Fib(N) for large N if you have the patience. 

Philip

-- 
You received this message because you are subscribed to the Google Groups "Java 
Posse" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/javaposse/-/g4qWAFL2eDAJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/javaposse?hl=en.

Reply via email to