# Modulus operator

I’d like to suggest to the powers-that-be that “modulo” or “modulus” be added to the operator section of the book, so that if someone searches it, that result will appear. I think it would make it easier to find for someone coming from another programming language, such as C.

I did find the “Arithmetic remainder” operator in the book. Perhaps simply adding (modulus) in parentheses next to “arithmetic remainder” would be adequate.

1 Like

It is called remainder in the rust world. You can find the documentation here:

https://doc.rust-lang.org/std/ops/trait.Rem.html

1 Like

But modulo in the “computer” world, so adding the term might very well be appropriate.

Thanks for the link with the extra details @hellow

2 Likes

It is called Remainder (I think) because it doesn’t have to be the modulo operation, but you can implement it for any type you want, e.g. (taken from the Rem example)

``````use std::ops::Rem;

#[derive(PartialEq, Debug)]
struct SplitSlice<'a, T: 'a> {
slice: &'a [T],
}

impl<'a, T> Rem<usize> for SplitSlice<'a, T> {
type Output = SplitSlice<'a, T>;

fn rem(self, modulus: usize) -> Self {
let len = self.slice.len();
let rem = len % modulus;
let start = len - rem;
SplitSlice {slice: &self.slice[start..]}
}
}

// If we were to divide &[0, 1, 2, 3, 4, 5, 6, 7] into slices of size 3,
// the remainder would be &[6, 7].
assert_eq!(SplitSlice { slice: &[0, 1, 2, 3, 4, 5, 6, 7] } % 3,
SplitSlice { slice: &[6, 7] });
``````

In this context modulo would not make much sense. Also if you think about it integer wise they give you the remaining value.

Maybe someone else can explain why they decided to call it Remainder?

1 Like

I think the reason is that ‘remainder’ and ‘modulus’ are different mathematically, with regard to handling negative values. I once looked this up because I was initially surprised to see rust’s `%` behave differently than the one in Haskell/Python.

``````Prelude> (-10) `mod` 20
10
``````
``````>>> (-10)%20
10
``````
``````fn main() {
assert_eq!((-10) % 20, -10);
}
``````

As I understand, Rust implements “remainder” whereas the two other languages implement “modulus”. See also this discussion:

3 Likes

I think OP’s problem is that they searched for “modulo” and the search didn’t turn up any results. I agree that that search should turn up the `%` operator, maybe labeled as

Arithmetic remainder (for positive integers, this is the modulo operation)

Or is there some way add the keywords “modulo” and “modulus” to that page, even when the words are not in the text?

4 Likes

It would be more honest, and I think less confusing, to just add a sentence that explicitly says that it is not the modulus operator, and preferably briefly explain the difference.

5 Likes