Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std.range.rotate? #9996

Open
dlangBugzillaToGithub opened this issue Aug 3, 2013 · 1 comment
Open

std.range.rotate? #9996

dlangBugzillaToGithub opened this issue Aug 3, 2013 · 1 comment

Comments

@dlangBugzillaToGithub
Copy link

bearophile_hugs reported this on 2013-08-03T13:09:02Z

Transfered from https://issues.dlang.org/show_bug.cgi?id=10754

CC List

  • crazymonkyyy

Description

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).
@dlangBugzillaToGithub
Copy link
Author

crazymonkyyy commented on 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;
}
```

@LightBender LightBender removed the P4 label Dec 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants