Skip to content

Instantly share code, notes, and snippets.

@Denommus
Last active January 3, 2016 04:49
Show Gist options
  • Select an option

  • Save Denommus/8411071 to your computer and use it in GitHub Desktop.

Select an option

Save Denommus/8411071 to your computer and use it in GitHub Desktop.
Tree implementation in Rust, both with mutable and immutable append.
use std::vec::append_one;
#[deriving(Clone)]
struct Tree<T>(T, ~[Tree<T>]);
impl<T: ToStr> ToStr for Tree<T> {
fn to_str(&self) -> ~str {
let &Tree(ref data, ref children) = self;
data.to_str() + " -> " + children.to_str()
}
}
impl<T> Tree<T> {
fn append_child_mut(&mut self, child: Tree<T>) {
let &Tree(_, ref mut children) = self;
children.push(child);
}
fn append_child_own(self, child: Tree<T>) -> Tree<T> {
let Tree(data, children) = self;
Tree(data, append_one(children, child))
}
}
impl<T: Clone> Tree<T> {
fn append_child(&self, child: Tree<T>) -> Tree<T> {
let &Tree(ref data, ref children) = self;
Tree(data.clone(),
append_one(children.clone(), child))
}
}
fn main() {
let mut test = Tree(1, ~[]);
test.append_child_mut(Tree(2, ~[]));
test.append_child_mut(Tree(3, ~[]));
println(test.to_str());
let tree = ~Tree(1, ~[]);
let tree2 = tree.append_child(Tree(2, ~[]));
let tree3 = tree.append_child(Tree(3, ~[]));
println(tree2.to_str());
println(tree3.to_str());
let foo = Tree(1, ~[]);
let foo2 = foo.append_child_own(Tree(2, ~[]));
let foo3 = foo2.append_child_own(Tree(3, ~[]));
println(foo3.to_str());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment