Last active
January 7, 2024 10:17
-
-
Save puffnfresh/6161753 to your computer and use it in GitHub Desktop.
Monoid trait and implementations in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Semigroup { | |
fn mappend(&self, b: Self) -> Self; | |
} | |
trait Monoid: Semigroup { | |
fn mempty() -> Self; | |
} | |
impl Semigroup for int { | |
fn mappend(&self, b: int) -> int { *self + b } | |
} | |
impl Monoid for int { | |
fn mempty() -> int { 0 } | |
} | |
impl Semigroup for ~str { | |
fn mappend(&self, b: ~str) -> ~str { *self + b } | |
} | |
impl Monoid for ~str { | |
fn mempty() -> ~str { ~"" } | |
} | |
fn main() { | |
println((~"Hello").mappend(~"World").to_str()); | |
println(1.mappend(2).to_str()); | |
// `as` didn't work as ascription. | |
let str_zero: ~str = Monoid::mempty(); | |
let int_zero: int = Monoid::mempty(); | |
println(str_zero); | |
println(int_zero.to_str()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@vi Monoid is not equivalent to Default.
Monoid must satisfy specific laws:
a.mappend(mempty()) == a
mempty.mappend(a) == a
Default mustn't.
Default may make sense without Semigroup, Monoid doesn't.