Skip to content

Instantly share code, notes, and snippets.

@j16r
Last active December 29, 2015 20:49
Show Gist options
  • Save j16r/7725877 to your computer and use it in GitHub Desktop.
Save j16r/7725877 to your computer and use it in GitHub Desktop.
An attempt to make a simple tree implementation in rust
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