On Monday, 17 January 2022 at 10:24:06 UTC, forkit wrote:
so I'm wondering why the code below prints:

1 2 3 4

and not

1 2 3 4 5

as I would expect.

foreach (value; 1..5) writef("%s ", value);

This kind of half-open interval, which includes the lower bound but excludes the upper bound, is used in programming because it lets you write

    foreach (i; 0 .. array.length) writef("%s ", array[i]);

...without going past the end of the array.

Edsger W. Dijkstra, a well-known academic computer scientist, has written in more detail about the advantages of this kind of interval: https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html

also, why is this not possible:

int[] arr = 1..5.array;

The `lower .. upper` syntax only works in foreach loops. If you want to create a range of numbers like this in another context, you must use the library function std.range.iota:

    import std.range: iota;
    int[] arr = iota(1, 5).array;

(Why "iota"? Because in APL, the Greek letter iota (ι) is used to create a range of numbers like this.)

Reply via email to