Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dlang slice and number range

Tags:

d

I'm not sure how to call the ".." operator in D. I have seen it for:

// Slicing 
int[] t = list[3..$];

// Looping
foreach (x; 1..10) {}

But it seems I can't use it in some "logical" places, for example:

int[] test = 1..N;
auto harmonic_serie = map!"1 / a"(1..1000);

Is ".." only syntaxic sugar that can only be used in slicing and looping? Are we forced to use the less readable std.range.iota?

like image 256
Nil Avatar asked Mar 22 '23 19:03

Nil


1 Answers

.. is only used for slicing, foreach, and ranged case statements. None of those contexts requires creating any kind of struct or list to do what it does. Slicing is basically just take and using two indices, and foreach is simply lowered to a for loop with a counter which starts at the first value and increments until it reaches the second. For .. to work in other contexts, it would need to be lowered to actual object of some kind or have some kind of list generated from the values, which is much more complicated (at least as far as the implementation goes). So, the language doesn't do any of that. For it to do something like what you're looking for, the compiler would have to actually be able to generate ranges, and all it understands about ranges is what's required to iterate over them with foreach.

std.range.iota actually creates a struct which is a range and doesn't require that the compiler or language understand anything about how it works. So, it can be used in places where you need an object to represent a range of values and .. won't work.

I'm sure that it's technically possible to make .. generate something like iota in other circumstances, but the approach taken by the D language designers at this point is that if something can be done in the library rather the the language, it should be done in the library, and if anything, they regret adding some features to the language rather than putting them in the library.

like image 166
Jonathan M Davis Avatar answered Apr 26 '23 22:04

Jonathan M Davis