foreach range with index
Steven Schveighoffer via Digitalmars-d
digitalmars-d at puremagic.com
Wed Jun 14 19:32:00 PDT 2017
On 6/14/17 6:02 PM, Ali Çehreli wrote:
> On 06/14/2017 12:22 PM, Steven Schveighoffer wrote:
>
>> 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.
>>
>> Compare with
>>
>> foreach(i, v; hashmap.enumerate)
>>
>> Intent is clear from the code.
>>
>> -Steve
>
> Then, perhaps we're arguing in favor of
>
> * writing .enumerate even for slices (implying that automatic indexing
> for them has been a historical artifact and code that wants to be
> portable should always write .enumerate)
>
> * making sure that enumerate() on arrays don't bring extra cost
I would say making enumerate on *any* range shouldn't bring any extra
cost over how foreach works on an array.
One idea I had but haven't thought it through completely is a way to
mark some parameter to foreach as always referencing the actual index,
so you aren't making unnecessary copies for the loop. When you foreach a
range, a copy is made just for the loop, and *then* a copy is made each
loop iteration for the element itself.
Maybe tagging a parameter in foreach as lazy means "always use the range
element".
-Steve
More information about the Digitalmars-d
mailing list