extending foreach for keyed ranges and other usage of datastructures

Quirin Schroll qs.il.paperinik at gmail.com
Thu May 16 20:59:26 UTC 2024


On Thursday, 16 May 2024 at 18:21:16 UTC, monkyyy wrote:
> On Thursday, 16 May 2024 at 18:15:09 UTC, Quirin Schroll wrote:
>> On Wednesday, 15 May 2024 at 20:27:12 UTC, monkyyy wrote:
>>> extend the api of foreach to allow for 
>>> `foreach(key,value;data)` for user data types,
>>>  and user defined "autodecoding"
>>>
>>> […]
>>
>> Can’t `opApply` not already do that?
>
> opApply cant effect T[] to have int indexes

Why would you want it to have `int` indices?

> and range.enumerate has problems with strings;

I have zero clue what you mean.

> if you have key,value pairs you must always use it in all 
> foreaches even if you only use value while slices get special 
> treatment

That’s definitely wrong. You can overload `opApply` just fine:
```d
struct Range
{
     import std.stdio;
     int opApply(int delegate(ref int) callback)
     {
         writeln("no key");
         return 0;
     }
     int opApply(int delegate(size_t, ref int) callback)
     {
         writeln("with key");
         return 0;
     }
}

void main()
{
     foreach (ref value; Range()) {} // writes "no key"
     foreach (key, ref value; Range()) {} // writes "with key"
}
```


More information about the dip.ideas mailing list