166 points · by matt_d · 2y ago · 182 comments
returns should be thought of as domesticated gotos but domesticated in the same way that cats are domesticated
As even their example mentions error handling
Goto sucks but not having proper exception handling sucks more
I had attended a summer class at Stanford on Data Flow Analysis, and took advantage. My compiler would break all the C flow control constructs into `if` and `goto` statements. Then, the optimizer would reconstruct the loops using graph algorithms.
Then, no matter what snarl of for, while, break, do-while, continue switch, or goto statements the programmer wrote, the optimizer could find all the loops, identify the loop variables, the loop header, etc. and then optimize it.
As a 68k coder (from Amiga)I often looked at the code generated and re-write the pinch points in assembler.
A Boyer-Moore text searching algorithm being one of them. The C code was nicked from Dr Dobbs.
This paper is documenting reality that is known to folks who practice the craft so in that sense it is not research as I would normally think of it. But it is useful documentation and so worth having written down.
I "practice the craft" (and I'm fully, gainfully, highly employed to practice the craft), I have a PhD in the "craft", I have published papers about the "craft", and I'm here to tell you IDGAF about what's terminologically research and what's not. I only care about well-written, detailed articles that explain a complex technical issue, problem, or solution.
There's not having to exaggerate and moreover there's value in rehashing known but tricky stuff
Well, only for those folks who you taint with C before you let them loose on compilers. If you follow something like https://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_... as your introduction, I doubt you would benefit from worrying about pitfalls of C.
The paper’s title is misleading in that way. It’s describing problems with loops, not problems with C loops.
[1] https://batsov.com/articles/2024/01/16/learning-ocaml-verify...
[2] https://www.scala-lang.org/api/current/scala/annotation/tail...
And Scala I haven't looked at in like a decade, but thinking about it I am not surprised it has similar protections. I feel like Clojure also had a keyword to recur as tail but probably been 12 years since I used that language so my memory could be completely faulty
Most programmers learn about loops pretty much at the absolute start of their development experience, where they don't yet have a way to talk about recursion. Don't even start about tail recursion or tail recursion optimisation.
I'd like to know how its unfortunate as well, I'm not sure I agree with this though.
int a = 0
begin:
if a == 10 {
jump :end
} else {
a = a + 1
jump :begin
}
end:
The programmer will have learnt that programs have a beginning and an end, they will have some notion of a variable, its type, and manipulating their values. They will even likely have learnt conditional branching logic. The only new concept here is that of jumping areas of code.If you next introduce methods you can clean it up and illustrate it more cleanly:
myFunc(int a) {
if a == 10 {
return
} else {
a = a + 1
return myFunc(a)
}
}
myFunc(0)
Finally you can explain the programmer "hey, there's this shortcut we can take called a loop that expresses this more succinctly": int a = 0
while (a != 10) {
a = a + 1
}
Nice simple-looking code. Yet this concept requires being able to grok much more than the relatively simple tail-recursive definition.Most people don't start out thinking like computers, so I think it's probably more important for a new student to understand how code describes a particular series of operations and then help them translate that into how a computer "thinks" about those operations.
I don't think your middle example would be obvious to most people learning about functions until they've had quite some time to get their heads around what functions do, even with the context of the top piece of code.
But why do you think we live in a world that likes to hide recursion? Why is it common for tree data structure APIs to expose visitors, rather than expecting you write your own recursive depth/breadth-first tree traversal?
Is there something innate in human nature that makes recursion less comprehensible than looping? In my career I've met many programmers who don't 'do' recursion, but none who are scared of loops.
And to me the weird thing about it is, looping is just a specialized form of recursion, so if you can wrap your head around a for loop it means you already understand tail call recursion.
I rarely use them because I became tired of having to explain them to others, where I've never had to explain a simple while loop that accomplishes the same thing with, usually literally, a couple more lines of code.
From all of my experience, recursion is usually at the expense of clarity, and not needed.
I think it's related to the door memory effect [1]: you loose the sense of state when hopping into the function, even though it's itself.
[1] https://www.scientificamerican.com/article/why-walking-throu...
Fundamentally, the actual state of the program does not match the abstract state used when programming a recursive function. You are recursively solving subproblems, but when something goes wrong, it becomes very hard to reason about all the partial solutions within the whole problem.
I'd be very shocked if anyone past the age of 4 or 5 had never heard (and learned to understand) statements like "Wash your hands until they're clean" which is a conditional loop (wash your hands, check if they're still dirty, repeat if they are, stop otherwise). If a teen or adult learning to program has trouble with conditional loops, I'd be very very surprised. The translation into programming languages (syntax) may be a challenge, the correct logical expressions for their intent may be a challenge, but the concept should not be.
Loops don't require coalescing the exit condition to a single flag (or even a single conditional expression). You can also use break (or your language's equivalent) to allow multiple exits from the same loop.
It has consequences, but it's first week sort of thing because it's so easy/relatable.
I rarely write loops where the relationship between the loop control variables has anything meaningful to say about what the iterations did.
This depends a lot on the background of the respective person. For someone who is more trained in classical mathematics, tail calls are more intuitive (or rather: nearer to their knowledge base) than while loops.
"Do this action 10 times" "Put one item in each box"
I fail to see how recursion is /more/ intuitive, in pretty much every (english) language construct I can think of the condition is separate from the action.
Everything else is just abstraction's we're built up to make our lives easier.
If we always jump to the top of the function, or if we jump someplace else, the machine cares not. Just don't blow the stack.
There are examples of other communities which have invented something pretty much the same as loop syntax, for example you get things which are basically loops in knitting patterns or (less reguarly) in recipes. I have never seen an example of recursion outside computer science/programming.
But take a newbie, and "do this 3 times" in a loop is far more clear than the recursive equivalent.
My dog => My friend's dog => My father's friend's dog => My father's sister's cousin's nephew's teacher's friend's plumber's dog's chew toy.
We can construct sentences like this with a completely arbitrary level of recursive nesting. It's so natural that people do it without thinking about it. Recursion only becomes unnatural when we prime people on it and get them thinking it's scary and complicated.
Darth Helmet: I am your father's brother's nephew's cousin's former roommate.
Lonestar: What does that make us?
Darth Helmet: Absolutely nothing.
In fact, standard English tends to avoid recursive relationships with specialized kinship terms based on ordinals like first cousins, first cousins once removed, great-, and so on. for (i = 0; i < n; ++i)
Now let's try to loop backward: for (i = n; i--; )
Why this thing is so asymmetric to the forward case? And doesn’t it, perhaps, start to become a little too idiomatic? Now, if we try to rewrite them with 'goto': i = 0;
a: <body>
++i;
if (i < n)
goto a;
i = n;
b: --i;
<body>
if (i > 0)
goto b;
Isn’t this more symmetric? Can we now see that the chief reason of asymmetry is that 'n' is not a valid value for 'i' but '0' is?'Goto' is, of course, an implementation detail and is not convenient for reasoning. Thing is loops are not necessary for reasoning either. They are an implementation detail mistakenly dressed into reasoning clothes.
It's possible to express it as a set of while loops (which someone on Stack Overflow showed [1]), but it's, IMO, less readable than the goto version. Of course, the recursive solution is the most readable anyway.
Edit: Also, both the goto version and while loop version of that algorithm on the Stack Overflow post have an out of bounds index when col and row are both zero. That algorithm was meant for 1-indexed arrays and was not properly translated.
[0]: https://cs.stanford.edu/%7Eknuth/fasc5b.ps.gz
[1]: https://stackoverflow.com/questions/78614303/can-knuths-algo...
void printManyStrsWithCommas(char *s[], int n /* trusted to be positive */)
{
int i = 0;
a: printOneStr(s[i]);
++i;
if (i < n) {
printOneStr(", ");
goto a;
}
}
Here the loop condition is 'i < n', but when it is true, we need to do one more thing (print a comma) before resuming the loop. If we are to stick with non-'goto' syntax we have the following options:- Somehow cram it into the loop expression with the comma operator. This is very limited because it is an expression. For example, what if 'printOneString' can err?
- Somehow use 'while(1)' with 'break'. It may even compile to the same code as with 'goto'. But why, then, we have to use an unbounded loop syntax with a clearly bounded sequence?
- Somehow add additional variables and tests and either lose efficiency or trust the compiler to lead us out.
With 'goto' the code does only what is necessary. What 'goto' does not do is that it does not immediately convey a clear idea that the code repeats certain steps.
for (i = 0; i < n; ++i);
for (i = n; i >= 0; --i);
(Note: not sure if intended that backward should run more often and include i = n) for (i = 0; i < n; i++)
for (i = n; --i >= 0; )
The second one could also be this: for (i = n - 1; i >= 0; i--)
I say this because your backwards loop accesses the inclusive range [0, n] while your forwards range accesses [0, n - 1].Your reverse iteration would result in an out of bounds access as well as unsigned integer overflow which results in an infinite loop.
Actually learning tail recursion and writing loops for it is a lot less necessary today than it was in the 1980s. It isn't necessary to teach it to beginners anymore because the compiler largely does the heavy lifting for us.
These days, tail recursion is a very advanced performance tuning trick, only used when you've positively identified your compiler version's implementation of your loop as the cause of slowness and you're willing to incur the increased code complexity for the increased performance.
for (int i = 0; i < 5; i++) {...}
vs
```let rec func_name counter = if counter = 5 then print "blast off!" else func_name (counter + 1)```
I don't really need to memorise the order of operations compared to a for loop (initialise, exit condition, increment) and I don't need to memorise if the exit condition means "execute while this is true" or "break the loop if this is true". That's just me though. I think the syntax for recursion is easier but loops might conceptually be easier to understand.
I think, better than both of those for the general case (and a good introduction) are "fold" functions and "foreach"-style loops, which iterate over every element in a list. I think those are used more often, and the reason you may want to do this is clearer to a student.
The for line ends up being one independent line they can grok, then free from their memory when looking inside the loop, knowing that I gets bigger for a while. From my experience, something like the recursion will blow away a beginners working memory, because they can't piecewise it. But, the biggest problem is the for loop is trivially expanded with the exact same format, you just shove stuff into the body. The recursion method requires significant reworking to expand. Beginners appreciate simple templates that they can understand and modify, because they're still putting it all together.
If I were writing the code in assembly, I would just use a loop, because that's what the machine is optimized to perform.
> But this is also a symptom of standard c's problem of not allowing one to define functions inside of functions.
There are extensions that do this; however, they cannot create a scoped closure for you so nobody cares to use them for anything.
> and these have to be coalesced into a single flag for the loop.
Or just use 'goto'.
The recursion in TCO can be implemented with a jump but it requires an explicit stack frame and ultimately it must return a value through that stack frame. Basic loops have no such requirements which allows you to do things like jump from the middle of one loop into the middle of a different one.
Granted, this is rare, and rarely useful in practice, but it occasionally is and the burden of restructuring these forms into TCO would actually reduce their clarity and performance.
> They are literally equivalent.
They are /functionally/ equivalent. The literal differences are meaningful and have definite performance implications.