extend foreach to work on non-arrays
IntegratedDimensions
IntegratedDimensions at gmail.com
Thu May 24 23:28:59 UTC 2018
On Thursday, 24 May 2018 at 23:08:39 UTC, aliak wrote:
> On Thursday, 24 May 2018 at 23:02:00 UTC, Neia Neutuladh wrote:
>> On Thursday, 24 May 2018 at 22:43:00 UTC, IntegratedDimensions
>> wrote:
>>> Doesn't make any sense?
>>>
>>> foreach(a; x)
>>>
>>> if x is not an array then a = x and the loop reduces simply
>>> and function to the case it is not so their can be no harm.
>>>
>>> It unifies the concepts so that one does not have to worry if
>>> x is an array or not and can offer no harm since when x is
>>> not an array everything simply reduces to an an alias of x.
>>
>> You can already do this for any type you define:
>>
>> class Foo
>> {
>> auto iterate() { return only(this); }
>> alias iterate this;
>> }
>>
>> Can you give examples of code that is awkward today that would
>> be simplified with your proposal? I don't expect people to
>> give full cost-benefit analyses for every suggestion, but it'd
>> be nice if you could at least mention some of the upsides.
>
> And then you can generalize this for any type
>
> auto elseOnly(T)(T t) {
> import std.range: isInputRange;
> static if (isInputRange!T) {
> return t;
> } else {
> import std.range: only;
> return only(t);
> }
> }
>
> foreach(i; 3.elseOnly) {
> }
>
> foreach(i; [1, 2, 3].elseOnly) {
> }
>
>
> Cheers
> - Ali
cool, and this is optimal, right? non-arrays are not converted in
to arrays, etc?
More information about the Digitalmars-d
mailing list