Rust: Add a method for computing the absolute difference between unsigned integers

Created on 25 Jun 2019  路  6Comments  路  Source: rust-lang/rust

Most helpful comment

distance is a good name, I think, as it is the mathematical term for abs(x-y).

I dislike @centril鈥檚 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).

All 6 comments

I suggest not calling it abs_sub due to the confusion created by the (terribly misnamed) function on floats, whose tortured legacy continues to this day in num_traits::Signed.

@ExpHP abs_diff perhaps?

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?

distance is a good name, I think, as it is the mathematical term for abs(x-y).

I dislike @centril鈥檚 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 distance seems too generic from the standpoint of a mathematical motivation, it is also used in the context of very different metric spaces than the normed space induced by the L1-norm. I think 'absolute difference' hits the nail on the head and with the given prior art of abbreviations that would make abs_diff my clear favorite. Similar to abs, checked_sub and other functions it doesn't seem necessary to add it in another way than as a method.

Was this page helpful?
0 / 5 - 0 ratings