Created
September 5, 2014 12:22
-
-
Save steveklabnik/0104fcbf0ffe08b34009 to your computer and use it in GitHub Desktop.
This file contains hidden or 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::Show; | |
use std::fmt::Formatter; | |
use std::fmt::FormatError; | |
enum Tree<T> { | |
Node(T, Box<Tree<T>>, Box<Tree<T>>), | |
Nil, | |
} | |
impl<T: Ord + Show> Tree<T> { | |
fn add(&mut self, val: T) { | |
match *self { | |
/* | |
Node(ref v, box Nil, box Nil) => { | |
if val >= *v { | |
*self = Node(v, box Nil, box Node(val, box Nil, box Nil)); | |
} else { | |
*self = Node(v, box Node(val, box Nil, box Nil), box Nil); | |
} | |
}, | |
*/ | |
format Node(ref v, ref mut l, ref mut r) => { | |
if val >= *v { | |
r.add(val); | |
} else { | |
l.add(val); | |
} | |
}, | |
Nil => { | |
*self = Node(val, box Nil, box Nil); | |
} | |
} | |
} | |
} | |
impl<T: Ord + Show> Show for Tree<T> { | |
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatError> { | |
match *self { | |
Node(ref v, ref l, ref r) => write!(f, "{} -> ( {} {} )", v, l, r), | |
Nil => write!(f, "Nil") | |
} | |
} | |
} | |
fn main() { | |
let mut t: Tree<int> = Node(2, box Nil, box Nil); | |
t.add(3); | |
println!("{}", t); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks a lot steve :) remove format in line 22 though.