Skip to content

Instantly share code, notes, and snippets.

@kindlychung
Last active September 15, 2016 16:22
Show Gist options
  • Save kindlychung/527558a2dcbbbd6cde3128c4cfc2a663 to your computer and use it in GitHub Desktop.
Save kindlychung/527558a2dcbbbd6cde3128c4cfc2a663 to your computer and use it in GitHub Desktop.
use std::ops::Add;
/// Z^m number system
/// # Examples
/// ```
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 {
if self.signum() != n.signum() {
(-self) % n
} else {
self % n
}
}
}
impl<i32> 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)
}
}
fn main() {
let x = Mod::new(5, 3);
let y = Mod::new(5, 2);
let z = x + y;
println!("{}", z.i);
}
cargo run
Compiling rustcallc v0.1.0 (file:///Users/kaiyin/Documents/workspace-eclipse-neon/rustcallc)
warning: unnecessary parentheses around `if` condition, #[warn(unused_parens)] on by default
--> src/main.rs:18:12
|
18 | if (self.signnum() != n.signnum()) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0046]: not all trait items implemented, missing: `Output`
--> src/main.rs:36:1
|
36 | impl Add for Mod<i32> {
| ^ missing `Output` in implementation
error: aborting due to previous error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment