Created
June 27, 2015 19:03
-
-
Save disolovyov/df29c2e0e65f315f10d8 to your computer and use it in GitHub Desktop.
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
use std::fmt; | |
use std::ops; | |
enum Nat { | |
Zero, | |
Succ(Box<Nat>) | |
} | |
impl ops::Add for Nat { | |
type Output = Nat; | |
fn add(self, other: Nat) -> Nat { | |
fn sum(a: Nat, b: Nat) -> Nat { | |
match a { | |
Nat::Zero => b, | |
Nat::Succ(nat) => Nat::Succ(Box::new(sum(*nat, b))), | |
} | |
} | |
sum(self, other) | |
} | |
} | |
impl fmt::Display for Nat { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
fn count(nat: &Nat) -> i32 { | |
match nat { | |
&Nat::Zero => 0, | |
&Nat::Succ(ref nat) => 1 + count(nat), | |
} | |
} | |
write!(f, "Nat({})", count(self)) | |
} | |
} | |
fn main() { | |
let a = Nat::Succ(Box::new(Nat::Succ(Box::new(Nat::Zero)))); | |
let b = Nat::Succ(Box::new(Nat::Succ(Box::new(Nat::Zero)))); | |
println!("Result: {}", a + b); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment