std.array.array seems to return flatten copy of input
Olivier Grant
against.the at evil.bots.com
Fri Apr 4 13:19:52 PDT 2014
Hi,
I've started using D as a scripting language at work and for
personal projects as a means to learn the language and I've
bumped into a case where I would like to iterate a slice by a
certain number of elements at a time such that :
foreach(s; [1,2,3,4].splice!(2))
{
writeln(s);
}
would print :
[1,2]
[3,4]
First of all, is there such a function in D's standard library as
I didn't seem to be able to find one ?
I ended up implementing the following :
import std.stdio;
import std.range;
import std.array;
auto splice( size_t N, R )( R range )
if(isInputRange!R)
{
struct Splicer
{
R array;
@property bool empty( ) const
{ return 0 == array.length; }
@property auto front( ) const
{ return array[0 .. N]; }
void popFront( )
{ array = array[N .. $]; }
}
static assert(isInputRange!Splicer);
assert(range.length % N == 0);
Splicer res = { range };
return res;
}
unittest
{
assert(equal([1,2,3,4].splice!(2), [[1,2],[3,4]]));
}
void main( )
{
auto a = [1,2,3,4];
writeln(a.splice!(2));
writeln(a.splice!(2).array);
}
which weirdly enough gives me the following output :
[[1,2],[3,4]] // I expect that.
[1,2,3,4] // But what is happening here ?
I'm obviously doing something wrong but I can't figure out what.
Thanks for the help in advance,
O.
More information about the Digitalmars-d-learn
mailing list