Skip to content

Instantly share code, notes, and snippets.

@tcsavage
Last active December 14, 2015 19:38
Show Gist options
  • Save tcsavage/5137637 to your computer and use it in GitHub Desktop.
Save tcsavage/5137637 to your computer and use it in GitHub Desktop.
trait Monoid {
static fn mempty() -> self;
fn mappend(other: self) -> self;
}
impl int: Monoid {
static fn mempty() -> int { 0 }
fn mappend(other: int) -> int { self + other}
}
// Generalise with foldable later
fn mconcat<M: Monoid>(elems: ~[M]) -> M {
let mut a: M = Monoid::mempty();
let mut i: uint = 0;
while i < elems.len() {
a=a.mappend(elems[i]);
i+=1;
}
return a;
}
// This works
fn sum(elems: ~[int]) -> int {
let mut a: int = 0;
let mut i: uint = 0;
while i < elems.len() {
a += elems[i];
i+=1;
}
return a;
}
fn main() {
let x: int = Monoid::mempty();
io::println(x.mappend(5).mappend(4).to_str());
let y: ~[int] = ~[5,6,7,8];
// io::println(mconcat(y).to_str());
io::println(sum(y).to_str());
io::println("Hello, world")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment