ixid:

I understand the basic use to slice an array but what about these:

foreach(i;0..5)
    dostuff;

That works yet this does not:

foreach(i;parallel(0..5))
    dostuff;

Why not let this work? It'd seem like a natural way of writing a parallel loop.

The design of D language is a bit of a patchwork, it's not very coherent. So the ".." notation defines an iterable interval only in a foreach (.. is used for switch cases too, but it includes the closing item too). Generally a "patchwork design" has some clear disadvantages, but it often has some less visible advantages too. With other people I have suggested few times for a..b to denote a first-class lazy range in D, but Walter was not interested, I guess. I'd like this, but using iota(5) is not terrible (but keep in mind that iterating on an empty interval gives a different outcome to iterating on an empty iota. I have an open bug report on this).


For some reason:

foreach(i;[0,1,2,3,4])
    dostuff;

This performs far more slowly than the first example

I don't know why, but maybe the cause is that an array literal like that induces a heap allocation. This doesn't happen with the lazy 0..5 syntax.


If it can do what it does in the first example why not let it do something like this:

int[] arr = 0..5; //arr = [0,1,2,3,4]

Because a..b is not a first-class interval, because lazyness and ranges were introduced quite late in D and not since the beginning of its design, so lazy constructs are mostly library-defined and they don't act like built-ins.


One final thought- why is the array function required to convert a lazy Result to an eager one? If you explicitly set something like int[] blah = lazything why not have it silently convert itself?

Beside the answers I've already given, generally because implicit conversions are often a bad thing. Requiring some syntax to denote the lazy->eager conversion is positive, I think I don't know of a language that perform such conversion implicitly.

Bye,
bearophile

Reply via email to