-
Notifications
You must be signed in to change notification settings - Fork 13.2k
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
A single method to rotate slices or vecs #65104
Comments
Could you provide a motivating example where having this method would greatly simplify the code? If you need it for your project, you can easilly roll your own implementaton using extension trait pattern: trait SliceExt {
fn rotate_signed(&mut self, rot: isize);
}
impl<T> SliceExt for [T] {
fn rotate_signed(&mut self, rot: isize) {
if rot >= 0 {
self.rotate_right(rot as usize)
} else {
let (abs, overflowed) = rot.overflowing_abs();
if overflowed {
self.rotate_left(isize::max_value() as usize + 1)
} else {
self.rotate_left(abs as usize)
}
}
}
} |
Thanks for your code but it looks very complex to me. Having only 2 named methods to rotate brings some problems when you want to use both inside a function. How are you going to program that with just rotate_right and rotate_left ? With signed numbers we could use a tuple parameter like (4, -4) to rotate right then left or (-4, 4) to do the opposite. |
You can rotate left or right with either method. If you want to rotate by a signed number, you can rotate by (There was originally only one method, which also took |
I do understand why you have made rotate_left and rotate_right. > "Ruby’s Array.rotate shifts left-ward, Python’s deque.rotate shifts That's true, but at least they have a solution. > "remove ambiguity about direction" Not true, see the above solutions. > "alleviating need to read docs" Reading the docs shall never be a problem and shall be recommended. > "make it easier for people who need to rotate right" That's a joke ??? I tend to prefer the Python's way. |
Let's say I want to rotate by -3 with your solution: fn main() {
let mut s: [u8; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let n: i8 = -3;
s.rotate_right(n.rem_euclid(s.len()) as usize);
println!("{:?}", s);
} Doesn't compile:
I ended up with: fn main() {
let mut s: [u8; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let n: i8 = -3;
s.rotate_right(n.rem_euclid(10) as usize);
println!("{:?}", s);
} Which works... But I think this could be clearer, less confusing, and probably faster, like this: fn main() {
let mut s: [u8; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let n: i8 = -3;
s.rotate(n);
println!("{:?}", s);
} |
Hello,
I know there's already 2 methods to rotate slices or vec (rotate_right and rotate_left).
But they both accept unsigned numbers exclusively.
Why not a single method which could accept a signed number ?
A positive number would turn to the right and a negative one to the left
The text was updated successfully, but these errors were encountered: