Last active
December 29, 2015 20:49
-
-
Save j16r/7725877 to your computer and use it in GitHub Desktop.
An attempt to make a simple tree implementation 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
use std::util::swap; | |
#[deriving(Eq)] | |
pub enum Tree { | |
Text(~str), | |
Cons(~Tree, ~Tree), | |
Nil | |
} | |
pub fn first<'r>(tree: &'r Tree) -> &'r Tree { | |
match *tree { | |
Cons(ref first, _) => { | |
let node: &Tree = *first; | |
node | |
} | |
_ => &Nil | |
} | |
} | |
pub fn rest<'r>(tree: &'r Tree) -> &'r Tree { | |
match *tree { | |
Cons(_, ref rest) => { | |
let node: &Tree = *rest; | |
node | |
} | |
_ => &Nil | |
} | |
} | |
pub fn next<'r>(tree: &'r Tree) -> &'r Tree { | |
first(rest(tree)) | |
} | |
pub fn append(tree: &mut Tree, node: Tree) { | |
match *tree { | |
Cons(_, ref mut tail @ ~Nil) => { | |
let end: &mut Tree = *tail; | |
swap(end, ~Cons(~node, ~Nil)) | |
} | |
Cons(_, ref mut rest) => { | |
let next: &mut Tree = *rest; | |
append(next, node) | |
}, | |
_ => fail!("appending() on non Cons node") | |
} | |
} | |
#[main] | |
fn main() { | |
let mut tree = ~Cons(~Nil, ~Nil); | |
assert!(first(tree) == &Nil); | |
assert!(rest(tree) == &Nil); | |
let head = Text(~"hello"); | |
append(tree, head); | |
println!("{:?}", tree) | |
//assert!(rest(tree) == &head); | |
//assert!(next(tree) == &Nil); | |
let tail = Text(~"world"); | |
append(tree, tail); | |
println!("{:?}", tree) | |
//assert!(rest(tree) == &head); | |
//assert!(next(tree) == &tail); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment