On 6/14/17 6:46 PM, Luís Marques wrote:
On Wednesday, 14 June 2017 at 19:22:24 UTC, Steven Schveighoffer wrote:
For example:

foreach(i, v; hashmap) => i is counter, v is value

Later hashmap adds support for iterating key and value. Now i is key,
v is value. Code means something completely different.

If we take a step back, I think we are discussing the generalization of
foreach. Let's assume we want to preserve the current foreach behavior
where associative types iterate with key and value pairs. If the
"hashmap" in your example was supposed to be an associative type then
`i` wasn't a counter, it was the key already. If "hashmap" didn't define
the iteration key (using a new kind of opApply or whatever) then it
wasn't an associative type, and therefore your change wouldn't be valid.

So, we just have to be careful that when foreach(i, v; foo) is
introduced the relevant types in phobos also implement the new behavior,
so that this situation doesn't arise afterwards..

The point I'm making is that we have mechanisms for a type to define what to do when you foreach with 2 parameters per loop iteration.

What you are proposing is to allow the compiler to define what to do in the case where the type doesn't. But what happens if it then defines the behavior later? code that was written expecting the first item to be an arbitrary index is now hijacked by the type to mean something else. This can't happen with arrays, because the language says so. The language doesn't have control over an arbitrary struct.

It could be any type, I just used a hypothetical hashmap that didn't already have key/value iteration. Probably an unlikely scenario, but it was what popped into my head as a demonstration.

And what if you DID want to iterate just an incrementing index with the values when the type defines 2-parameter iteration otherwise? That mechanism isn't available to you without some effort. So again, we still need an enumerate to do what you want.

-Steve

Reply via email to