sniffnoy: (SMPTE)
[personal profile] sniffnoy
I'm trying to just write down more old thoughts, and you know what, I haven't written this one down.

The Python programming language has an interesting construct I haven't seen elsewhere: while/else. A while block with an else block following. Now this is terribly misnamed; based on the name you'd think that, like, the else block executes if the while block ends up being skipped, like if/else, but that's not what it is. The way it actually works that the else block executes after the while block *unless* you broke out of the while block.

This is misnamed -- it should be called something like while/coda or while/then -- but I think this is a nice enough construct that it should be standard! Yes, obviously just like labeled breaks this can be replicated by setting a flag or whatever (and often is), but it would still be nicer to just have it directly.

In particular, it really bugs me that Rust in particular doesn't have it, and here's why. Rust has this neat feature where any block can return a value (indeed, *does* return a value -- if it doesn't seem to, it's returning a value of unit type), and in a loop block, when you break, you can specify a value, and then the loop returns a value! That's pretty neat!

But, while you can do this from a loop block, you can't do this (with a non-unit type) from a while block! Why not? Because if the while block concludes naturally, what value would it return? The only sensible thing is to say that the while block returns unit type -- since it must return a consistent type -- but that means it can't return a non-unit value, you can't break out of it with a value. But if you could add a coda to a while block, this wouldn't be a problem anymore!

(Obviously all of this also implies to other types of looping blocks that naturally terminate.)

This lack of consistency really bugs me, and it's something that people have repeatedly suggested adding, but it's never been added because they haven't come up with a syntax for it that is both clear and not too breaking. (Apparently breaking out of a loop with a value was a somewhat late addition to Rust, which is why this wasn't gotten right at the beginning.) Boo! Anyway yeah it bugs me.

June 2025

S M T W T F S
1234567
891011121314
15161718192021
2223 2425262728
2930     
Page generated Jun. 28th, 2025 08:59 pm
Powered by Dreamwidth Studios