logoalt Hacker News

tialaramextoday at 2:18 AM1 replyview on HN

You list a few absences but absences aren't the end of the world, I say it's worse when designers make a booboo where the language semantics are wrong. In C++ there are so many of these it's not sporting but a recurring example from the garbage collected languages would be the for-each loop mistake.

Several times now†, people make a language where the way a for-each loop (for each Goose in Geese ...) works is that there's a single variable Goose and each time around the loop we change which value is referred to by the Goose variable. This seems intuitively like a reasonable way to do this. But it's wrong and eventually your programmers will get nasty surprises. What you actually should deliver is an implementation where each time around the loop there's a new variable named Goose, that variable goes away at the end of that iteration and will be replaced by the next one, with the same exact name.

† At least Go and C#, I think there are others


Replies

lelanthrantoday at 6:15 AM

> What you actually should deliver is an implementation where each time around the loop there's a new variable named Goose, that variable goes away at the end of that iteration and will be replaced by the next one, with the same exact name.

Is this because a closure inside a loop will capture a reference to `Goose`?

I think that this is a capture problem not a variable problem. The closure should always do the right thing and capture the value of all variables (not just ones inside the loop), instead of capturing the reference to the variables.

Then the general problem is fixed to match what developers expect, instead of a specific instance of that class of problems being fixed and working differently to how other captured variables work.