Skip to content

Instantly share code, notes, and snippets.

@lvicentesanchez
Created April 7, 2016 14:02
Show Gist options
  • Save lvicentesanchez/e6828315caecafedf54a3968167dfa97 to your computer and use it in GitHub Desktop.
Save lvicentesanchez/e6828315caecafedf54a3968167dfa97 to your computer and use it in GitHub Desktop.
Monoid implementation in Rust
trait Empty {
fn empty() -> Self;
}
trait Semigroup {
fn append(&self, other: Self) -> Self;
}
trait Monoid : Semigroup+Empty {}
impl Empty for i32 {
fn empty() -> i32 { 0 }
}
impl Semigroup for i32 {
fn append(&self, other: i32) -> i32 { self + other }
}
impl Monoid for i32 {}
fn sum<T: Semigroup>(a: T, b: T) -> T { a.append(b) }
fn main() {
println!("1 + 1 = {}", sum(1, 1));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment