concept tail call optimization in category erlang

appears as: tail call optimization
Erlang and OTP in Action

This is an excerpt from Manning's book Erlang and OTP in Action.

You can rely on tail call optimization

You’re probably aware that behind the scenes, each process uses a stack to keep track of what it needs to go back and do later while it’s running the program (such as “remember to go back to this spot and add N afterward”). The stack is a last-in-first-out data structure, like a heap of notes stacked on top of each other; and of course, if you keep adding more things to remember, you’ll run out of memory. That’s not a good thing if you want your server to run forever, so how can Erlang use only recursive calls for loops? Doesn’t that add more stuff to the stack on each call? The answer is no, because Erlang guarantees tail call optimization.

Tail call optimization means that when the compiler sees that a call is a tail call (the last thing that needs to be done before returning), it can generate code to throw away the information about the current call from the stack before the tail call is performed. Basically, the current call has no more real work to do, so it says to the function that it’s about to tail call: “Hey! When you’re finished, hand over your result directly to my parent. I’m going to retire now.” Hence, tail calls don’t make the stack grow. (As a special case, if the tail call is a recursive call back to the same function, it can reuse much of the info on top of the stack rather than throwing away the note to re-create it.) Essentially, a tail call becomes “clean up if needed, and then jump.” Because of this, tail recursive functions can run forever without using up the stack, and they can be as efficient as a while loop.

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest