Skip to content

Instantly share code, notes, and snippets.

@amazari
Created April 27, 2014 14:04
Show Gist options
  • Save amazari/11346398 to your computer and use it in GitHub Desktop.
Save amazari/11346398 to your computer and use it in GitHub Desktop.
trait Monoid {
fn zero() -> Self;
fn append(this: Self, that: Self) -> Self;
}
impl Monoid for int {
fn zero() -> int { 0 }
fn append (this: int, that: int) -> int { this + that }
}
fn fold<T : Monoid> (slice: &[T]) -> T {
return slice.iter().fold(T::zero(), |acc, v| T::append(acc, v));
}
fn main() {
let xs: [int, ..5] = [1, 2, 3, 4, 5];
println!("{}", fold(xs));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment