On Sunday, 25 February 2018 at 05:24:54 UTC, psychoticRabbit
wrote:
Hi. Anyone know whether something like this is possible?
I've tried various conversions/casts, but no luck yet.
Essentially, I want to cast the result set of the iota to an
array, during initialisation of the variable.
You can't do that, because iota is a range and only exists as a
range struct on the stack.
Think about it as a struct with three variables (start, end,
stepSize) - not as an array.
Of course, iota is a lot smarter than that as things like
`10.iota[3 .. $]` or `3 in 10.iota` work, but it's important to
notice that e.g. `iota[1 .. 2]` just returns a new range object.
No GC allocation happens here and "the array" never actually
exists in memory.
no, I don't want to use 'auto'. I want an array object ;-)
This has nothing to do with auto. Auto is just a filler word for
the compiler that says: "whatever is the type of the declaration,
use this as the type".
In other words, the compiler does this automatically for you:
---
typeof(10.iota) r = 10.iota;
---
Anyhow it looks like what you want to do is to __allocate__ an
array. You can do so with std.array.array.
---
import std.array, std.range;
void main()
{
int[] arr = 10.iota.array;
}
---
https://run.dlang.io/is/kKSzjH
Again, notice that the actual implementation of array is this (in
the non-optimized case):
---
auto array(Range)(Range r)
{
auto a = appender!(E[])(); // <- allocation happens in the
appender
foreach (e; r)
a.put(e);
return a.data;
}
---
(without constraints for simplicity)
Of course, Phobos has a more sophisticated version of
std.array.array, but it's basically like this:
https://github.com/dlang/phobos/blob/master/std/array.d#L97
--------------
module test;
import std.stdio;
import std.range : iota;
void main()
{
int[] intArr = iota(1, 11); // 1..10
double[] doubleArr = iota(1.0, 11.0); // 1.0..10.0
char[] charArr = iota('a', '{'); // a..z
}
-------------