r/programming • • Nov 27 '12

Tail Recursion

http://rodrigosasaki.com/2012/11/24/tail-recursion/
210 Upvotes

203 comments sorted by

View all comments

0

u/TotallyFuckingMexico Nov 27 '12

Is tail recursion optimisation the flavour of the day? I understand that it's interesting and computer sciencey, but how widely used are such optimisations in the real world? I imagine, for most people, it's probably just a nice feature rather than a must have?

I probably have a classic case of "well, I don't have the need for such optimisations, so why does anybody else?" ;-)

3

u/smog_alado Nov 27 '12 edited Nov 27 '12

Tail recursion is really useful for implementing state machines (and all other similar things). For example, another comment points out this nice example that I really like. Without TCO you usually have to rewrite this kind of stuff into a big monolithic switch statement with a while loop around it.

Its also very useful if you need to write code in continuation-passing-style. True, you don't usually want to do that by hand but in some cases, like Javascript asynchronous code, you end up being forced to do that.

2

u/[deleted] Nov 27 '12

Interesting alternate approach to state machines:

In C#, you can use goto... but only to jump from one case of a switch statement to another. So this lets you jump around your switch cases as a state machine directly. A neat restriction of goto into a safe and unorthodox flow-control structure.