Coincidentally, I had a stack overflow while working on some trees a few months ago, it ate all my ram within about 2 seconds. Although my stack was sizeable, my program was blind and unaware of the stack limit.
So, thanks to that, we can define map the clear and easy way:
(define (map f l)
(if (pair? l)
(cons (f (car l))
(map f (cdr l)))
'()))
Instead of the more wasteful, less readable way: (define (map f l)
(let lp ((l l) (out '()))
(if (pair? l)
(lp (cdr l) (cons (f (car l)) out))
(reverse out))))
[0] https://gnu.org/software/guile/docs/master/guile.html/Stack-...That said, it is a nice way to reduce the chance or delay the occurrence of hitting the stack limit (whether it's on the heap or an explicit stack that's still what's happening).
Is TCO used in C++? I've only ever seen it mentioned in reference to Scheme and Haskell. It's a compiler optimization, so it would be transparent to the programmer, right?
That is an implementation detail. It doesn't matter if it is does at compiler or whatever runtime is targeted.
This is called lowering in compiler design speak.
Closures? Can't be optimized. Polymorphic method? Can't be optimized (even if every implementation is tail recursive).
This is more than an implementation detail, it actively influences the way you write your code.
And Scala -doesn't- optimize A calls B calls A etc cases. It requires the developer to explicitly make use of scala.util.control.TailCalls. See http://www.scala-lang.org/api/2.11.2/index.html#scala.util.c... and associated white paper.
What Scala gives you is that if A calls A (calls A calls A), and is tail recursive, and A can not be overridden, it will optimize it.
[0] "The Joy of Clojure," Fogus and Houser
As far as I know, F# is the only reasonably popular .NET language to emit the tail. prefix, though[3].
[1] http://blogs.msdn.com/b/davbr/archive/2007/06/20/tail-call-j...
[2] http://blogs.msdn.com/b/clrcodegeneration/archive/2009/05/11...
[3] http://blogs.msdn.com/b/fsharpteam/archive/2011/07/08/tail-c...
When people talk of "Tail Call Optimization" (TCO) they are talking about a way to recurse without leaving things on the stack (tail-call meaning that the recuse call is the last thing in the function so the state of the function doesn't need pushed on the stack, it can be discarded.