Remix.run Logo
tialaramex a day ago

Forbidding recursion is pretty annoying. One of the nice things that's on the distant horizon for Rust is an explicit tail recursion operator perhaps named `become`. Unlike naive recursion, which as this video (I haven't followed the link but I'm assuming it is Laurie's recent video) explains risks stack overflow, optimized tail recursion doesn't grow the stack.

The idea of `become` is to signal "I believe this can be tail recursive" and then the compiler is either going to agree and deliver the optimized machine code, or disagree and your program won't compile, so in neither case have you introduced a stack overflow.

Rust's Drop mechanism throws a small spanner into this, in principle if every function foo makes a Goose, and then in most cases calls foo again, we shouldn't Drop each Goose until the functions return, which is too late, that's now our tail instead of the call. So the `become` feature AIUI will spot this, and Drop that Goose early (or refuse to compile) to support the optimization.

tgv a day ago | parent | next [-]

In C, tail recursion is a fairly simple rewrite. I can't think of any complications.

But ... that rewrite can increase the cyclomatic complexity of the code on which they have some hard limits, so perhaps that's why it isn't allowed? And the stack overflow, of course.

AnimalMuppet a day ago | parent [-]

I don't know that it's just cyclomatic complexity. I think it at least part of it is proving that you meet hard real-time constraints. Recursion is harder to analyze that way than "for (i = 0; i < 16; i++) ... " is.

morshu9001 12 hours ago | parent | prev | next [-]

Thinking recursively is one thing, but can't remember the last time I've wanted to use recursion in real code.

zozbot234 a day ago | parent | prev [-]

The tail recursion operator is a nice idea, but the extra `become` keyword is annoying. I think the syntax should be `return as`: it uses existing keywords, is unambiguous and starts with `return` which tail recursion is a special case of.

tialaramex a day ago | parent [-]

Traditionally the time for bike shedding the exact syntax is much closer to stabilization.

Because Rust is allowed (at this sort of distance in time) to reserve new keywords via editions, it's not a problem to invent more, so I generally do prefer new keywords over re-using existing words but I'm sure I'd be interested in reading the pros and cons.

zozbot234 a day ago | parent [-]

The usual argument against a decorated `return` keyword is that a proper tail call is not a true "return" since it has to first drop any locals that aren't passed thru to the tail call. I don't think it's a very good argument because if the distinction of where exactly those implicit drops occur was that important, we'd probably choose to require explicit drops anyway.