\$\begingroup\$

A \$Z^m\$ number system includes integers in the interval \$[0, m)\$ when \$m > 0\$ or \$(m, 0]\$ when \$m < 0\$. The code defines a trait Mod to represent numbers in this system and the + , - , and * operator for it.

use std::ops::Add; use std::ops::Mul; use std::ops::Sub; struct Mod<T: Modulo<T>> { modulo: T, i: T, } trait Modulo<T> { fn modulo(&self, n: T) -> T; } impl Modulo<i32> for i32 { fn modulo(&self, n: i32) -> i32 { let mut x: i32 = *self; while x.signum() != n.signum() { x += n; } x % n } } impl Mod<i32> { fn new(modulo: i32, i: i32) -> Mod<i32> { let n = i.modulo(modulo); Mod { modulo: modulo, i: n, } } } impl Add for Mod<i32> { type Output = Mod<i32>; fn add(self, other: Mod<i32>) -> Mod<i32> { Mod::new(self.modulo, self.i + other.i) } } impl Sub for Mod<i32> { type Output = Mod<i32>; fn sub(self, other: Mod<i32>) -> Mod<i32> { Mod::new(self.modulo, self.i - other.i) } } impl Mul for Mod<i32> { type Output = Mod<i32>; fn mul(self, other: Mod<i32>) -> Mod<i32> { Mod::new(self.modulo, self.i * other.i) } } fn main() { let x = Mod::new(-5, 3); let y = Mod::new(-5, 8); println!("{}", (x + y).i); let x = Mod::new(-5, 3); let y = Mod::new(-5, 8); println!("{}", (x - y).i); let x = Mod::new(-5, 3); let y = Mod::new(-5, 8); println!("{}", (x * y).i); }

All suggestions are welcome, but I am particularly interested in: