4 ms·
>A tail call is basically goto with arguments. Every function call is "goto with arguments". Sometimes there's even an argument that tells the code block where
by wyager 12y ago
>A tail call is basically goto with arguments.
Every function call is "goto with arguments". Sometimes there's even an argument that tells the code block where to jump back to when it's done.
>Like a goto, it's useful but potentially confusing.
How is it confusing? You don't even have to be aware of TCO to take advantage of it. Many recursive algorithms are tail-call-optimizable out of the box.
>You shouldn't use it when a more structured loop construct will work.
Ironically, there are many programmers who consider loops to be too low-level and unstructured compared to recursive algorithms.
- dottrap 12y agoThere is a really nice example of the "goto" semantic for proper tail calls in "Programming in Lua". The example is a maze or adventure game where you need to move into different rooms (north, south, east west). http://www.lua.org/pil/6.3.html http://www.lua.org/pil/6.3.html It's a nice example because it's simple, it doesn't confuse/intermix the concept with recursion, and it's an effective solution because it allows you to achieve the goal of moving to rooms (i.e. s state machine) elegantly. And in a language without proper tail recursion, it is easy to envision how you could accidentally blow up the call stack.
- foldr 12y agoLoops are a much higher level construct than tail calls. It's much easier to make a mistake iterating through a list using tail calls than it is using a loop or a higher order function. (E.g. you can forget to handle the base case.)
- fpgeek 12y agoWhile I agree that higher-order functions are higher-level than tail calls, I'd say that the prevalence of things like off-by-one errors makes the comparison between loops and tail calls far more ambiguous.
- foldr 12y agoI was thinking more of for-each loops etc. than low-level loops with explicit counters/iterators.