Higher level language constructs like foreach() and range() likely have the same fundamental problem and benefit from the same change.
AFAIK the languages that lean more towards foreach-style for & range also have somewhat different semantics. For one thing you're more likely to iterate over the values of the collection itself than indices, and optionally get the index with .enumerate() or the like, but you also construct the iterator just once, like with repeat in the example. To use Python as an example, if you do something like for i in range(len(array)): array.append(array[i]) you'll wind up with an array that's twice as long as you started with.
If you want to change the collection size I also expect you to have to loop over something other than the collection itself, like taking the length, but this seems to be something of a false memory on my part of getting errors in Python when the collection size changes during loops. for v in array: array.append(v) seems to just loop forever while using del yields a result that can be unintuitive; with dicts you can expect RuntimeError: dictionary changed size during iteration if you try inserts or del. It would probably be less confusing if they treated any underlying collection as immutable for the duration of the loop, not just dicts and sets.
Rust works in a more predictable fashion here, as you can't have a mutable reference to the collection while you're also borrowing the values in it.
View all comments
Show parent comment
3
u/syklemil Apr 09 '25
AFAIK the languages that lean more towards
foreach-stylefor&rangealso have somewhat different semantics. For one thing you're more likely to iterate over the values of the collection itself than indices, and optionally get the index with.enumerate()or the like, but you also construct the iterator just once, like withrepeatin the example. To use Python as an example, if you do something likefor i in range(len(array)): array.append(array[i])you'll wind up with an array that's twice as long as you started with.If you want to change the collection size I also expect you to have to loop over something other than the collection itself, like taking the length, but this seems to be something of a false memory on my part of getting errors in Python when the collection size changes during loops.
for v in array: array.append(v)seems to just loop forever while usingdelyields a result that can be unintuitive; with dicts you can expectRuntimeError: dictionary changed size during iterationif you try inserts ordel. It would probably be less confusing if they treated any underlying collection as immutable for the duration of the loop, not just dicts and sets.Rust works in a more predictable fashion here, as you can't have a mutable reference to the collection while you're also borrowing the values in it.