On Tuesday, 9 January 2024 at 13:22:24 UTC, bachmeier wrote:
On Tuesday, 9 January 2024 at 10:11:35 UTC, Alexibu wrote:
It looks like isInputRange is false for arrays with fixed
length by design.
I can do:
```d
float[4] arr;
foreach(x;arr)
writefln("%s",x)
```
but not :
```d
arr.each!(a => a.writefln("%s",a));
```
Is there a good reason for this ?
It took my a long time to figure out.
Jonathan's been giving you good general information about this.
I'm curious about your partial example. If I fix the writefln
call, it works.
```
import std;
float[4] arr;
void main() {
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr.each!(a => "%s".writefln(a));
}
```
You're right. My original problem was with the map algorithm, and
I changed the example to make it simpler thinking all range
algorithms would be the same.
If each works, I can't see why map filter etc can't work
consistently where they only need an input range.
```d
auto line = arr.filter!(a > 0).map!(a =>
a.to!string).joiner("\t").text;
```
Should be fine because each result range is passed on the stack
to the next algorithm, and then at the end the text (or array)
algorithm doesn't return a range.
Also this should be fine because the ranges are all used on the
stack.
```d
float[6] array;
string[] result;
auto line = arr.filter!(a > 0).map!(a => a.to!string).each(a =>
result ~= a);
return result;
```
If someone keeps ranges around longer than the static array then
there are the problems Jonathan is describing.
```d
float[6] array;
auto filtered = arr.filter!(a > 0);
return filtered;
```
I wonder if the compiler could tell if you are only using the
range as a temporary argument as opposed to assigning it to a
variable ? Is there that rvalue lvalue distinction in D ?
Obviously anything that adds or removes values won't work, and as
Jonathan points out returning a slice from find etc would be a
slice to a static array which could cause problems.
I don't actually use static arrays very often but they can be
convienient, especially if you were trying to convert maths or
scientific code from something like matlab or numpy.