Skip to content

Instantly share code, notes, and snippets.

@disolovyov
Created June 27, 2015 19:03
Show Gist options
  • Save disolovyov/df29c2e0e65f315f10d8 to your computer and use it in GitHub Desktop.
Save disolovyov/df29c2e0e65f315f10d8 to your computer and use it in GitHub Desktop.
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