Skip to content

Instantly share code, notes, and snippets.

@rrichardson
Last active August 29, 2015 14:04
Show Gist options
  • Save rrichardson/4e63b4b4189f2c486bdf to your computer and use it in GitHub Desktop.
Save rrichardson/4e63b4b4189f2c486bdf to your computer and use it in GitHub Desktop.
recursion in rust.. looks like hieroglyphics
use std::fmt::Show;
trait Mappable<T> {
fn each<'r>(&self, f: &mut |&T|: 'r -> ());
fn map<'r, B>(&self, f: &mut |&T|: 'r -> B) -> Vec<B>;
}
enum BinaryTree<T> {
Leaf(T),
Child(T, Box<BinaryTree<T>>, Box<BinaryTree<T>>),
Null
}
fn create_binary_search_tree(vector: Vec<int>) -> BinaryTree<int>{
fn insert_node<T: Copy+Ord+Show>(val: T, btree: BinaryTree<T>) -> BinaryTree<T> {
match btree {
Leaf(tval) if val > tval => Child(tval, box Null, box Leaf(val)),
Leaf(tval) if val < tval => Child(tval, box Leaf(val), box Null),
Child(tval, left, right) => match val.cmp(&tval) {
Greater => Child(tval, left, box insert_node(val, *right)),
Less => Child(tval, box insert_node(val, *left), right),
Equal => fail!("already has a node with {}", tval),
},
Null => Leaf(val),
Leaf(lval) if val == lval => Leaf(val),
_ => Null
}
}
vector.iter().fold(Null, |a, &b| insert_node(b, a))
}
impl<T: Copy+Ord+Show> Mappable<T> for BinaryTree<T> {
fn map<'r, B>(&self, f: &mut |&T|: 'r -> B) -> Vec<B> {
fn traverse<'r, T, B>(btree: &BinaryTree<T>, f: &mut |&T|: 'r -> B, acc: &mut Vec<B>) {
match *btree {
Leaf(ref tval) => acc.push((*f)(tval)),
Child(ref tval, ref left, ref right) => {
acc.push((*f)(tval));
traverse(&**left, f, acc);
traverse(&**right, f, acc);
},
Null => return
}
}
let mut vec = Vec::new();
traverse(self, f, &mut vec);
return vec;
}
fn each<'r>(&self, f: &mut |&T|: 'r -> ()) {
match *self{
Leaf(ref tval) => (*f)(tval),
Child(ref tval, ref left, ref right) => {
(*f)(tval);
left.each(f);
right.each(f);
},
Null => return
}
}
}
fn main() {
let t = create_binary_search_tree(vec![1,2,3,4,5,6,7,8,9]);
t.each(&mut |a| -> () { println!("Node: {}", a); });
let result = t.map(&mut |a| -> int { *a * *a });
for i in result.iter() {
println!("> {}", i);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment