-
Notifications
You must be signed in to change notification settings - Fork 12.9k
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
Add a method for computing the absolute difference between unsigned integers #62111
Comments
I suggest not calling it |
@ExpHP |
abs_difference ? |
What do you think about adding: fn abs_difference<T: Sub<Output = T> + Ord>(x: T, y: T) -> T {
if x < y {
y - x
} else {
x - y
}
} instead of doing it on just the unsigned integer types? |
I dislike @Centril’s above generalization, as what it does is unrelated with the name of the function in most cases (the first thing that comes to mind is that something called an « absolute difference » should be a non-negative real number). |
The term |
Until that happens, I've found the easiest way to do this is: |
If no one has any objections I can make a pull request implementing the following functions: fn abs_diff(slf: u8, other: u8) -> u8;
fn abs_diff(slf: u16, other: u16) -> u16;
fn abs_diff(slf: u32, other: u32) -> u32;
fn abs_diff(slf: u64, other: u64) -> u64;
fn abs_diff(slf: u128, other: u128) -> u128;
fn abs_diff(slf: usize, other: usize) -> usize;
fn abs_diff(slf: i8, other: i8) -> u8;
fn abs_diff(slf: i16, other: i16) -> u16;
fn abs_diff(slf: i32, other: i32) -> u32;
fn abs_diff(slf: i64, other: i64) -> u64;
fn abs_diff(slf: i128, other: i128) -> u128;
fn abs_diff(slf: isize, other: isize) -> usize; where for unsigned types the implementation would be fn abs_diff(slf: U, other: U) -> U {
if slf < other {
other - slf
} else {
slf - other
}
} and for signed types fn abs_diff(slf: I, other: I) -> U {
if slf < other {
(other as U).wrapping_sub(slf as U)
} else {
(slf as U).wrapping_sub(other as U)
}
} Especially the latter is a useful contribution as it is somewhat non-trivial and tricky to write correctly as a user, if you are not intimately familiar with two's complement. |
Added abs_diff for integer types. Closes rust-lang#62111.
Added abs_diff for integer types. Closes rust-lang#62111.
Added abs_diff for integer types. Closes rust-lang#62111.
Added abs_diff for integer types. Closes rust-lang#62111.
Just sharing some experience from the wild: I have code of the form // a and b are i16
if a > b {
let c = a.abs_diff(b) as usize;
// do something with c
} where I check |
See discussion in #62103 (comment).
The text was updated successfully, but these errors were encountered: