Comment #0 by bearophile_hugs — 2013-08-03T13:09:02Z
std.algorithm.bringToFront is efficient to rotate arrays in-place, but often in range-based coding (in UFCS chains) I'd like a lazy range that yields the rotated items and doesn't modify the order of the items of the original data. So in Phobos I'd like a lazy range with a semantics similar to this:
import std.stdio, std.range;
auto rotate(R)(R r, in int n) pure nothrow
if (isRandomAccessRange!R) {
immutable int len = r.walkLength;
return r.cycle.drop(n >= 0 ? n : len + n).take(len);
}
void main() {
foreach (shift; -5 .. 5)
[10, 20, 30, 40, 50].rotate(shift).writeln;
}
To work like this the input array should be a random access one. (You can write a rotate() for a bidirectional array, but I think there is less need for it).
Comment #1 by crazymonkyyy — 2022-09-10T15:44:48Z
I also dislike the wonky bringToFront; tho I think it should be in place
my take:
```d
void rotate(T)(T foo,int i){
auto bar=foo.cycle.drop(i).take(foo.length).array[];
foreach(ref e;foo){
e=bar.front;
bar.popFront;
}}
unittest{
auto foo=[1,2,3,4,5];
foo.rotate(2);
foo.writeln;
}
```
Comment #2 by robert.schadek — 2024-12-01T16:18:32Z