Last active
May 7, 2018 17:44
-
-
Save doxxx/a51261b5f295a4d513c41797d5c14b86 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
enum BinaryTree<T> { | |
Leaf(T), | |
Branch(Box<BinaryTree<T>>, T, Box<BinaryTree<T>>), | |
} | |
trait TreeWeight<T> | |
where | |
T: std::ops::Add<Output = T> + Copy, | |
{ | |
fn tree_weight(&self) -> T; | |
} | |
impl<T> TreeWeight<T> for BinaryTree<T> | |
where | |
T: std::ops::Add<Output = T> + Copy, | |
{ | |
fn tree_weight(&self) -> T { | |
match *self { | |
BinaryTree::Leaf(payload) => payload, | |
BinaryTree::Branch(ref left, payload, ref right) => { | |
left.tree_weight() + payload + right.tree_weight() | |
} | |
} | |
} | |
} | |
trait Traversal<T> { | |
fn traverse<F>(&self, cb: &F) | |
where | |
F: Fn(&T); | |
} | |
impl<T> Traversal<T> for BinaryTree<T> { | |
fn traverse<F>(&self, cb: &F) | |
where | |
F: Fn(&T), | |
{ | |
match *self { | |
BinaryTree::Leaf(ref payload) => cb(payload), | |
BinaryTree::Branch(ref left, ref payload, ref right) => { | |
left.traverse(cb); | |
cb(payload); | |
right.traverse(cb); | |
} | |
} | |
} | |
} | |
fn print_payload<T>(payload: &T) | |
where | |
T: std::fmt::Display, | |
{ | |
println!("payload: {}", payload); | |
} | |
fn main() { | |
let tree_int = BinaryTree::Branch( | |
Box::new(BinaryTree::Leaf(5)), | |
10, | |
Box::new(BinaryTree::Leaf(3)), | |
); | |
println!("weight: {}", tree_int.tree_weight()); | |
tree_int.traverse(&print_payload::<i32>); | |
// alternatively: tree_int.traverse(&|p| println!("payload: {}", p)); | |
let tree_float = BinaryTree::Branch( | |
Box::new(BinaryTree::Leaf(12.34)), | |
11.22, | |
Box::new(BinaryTree::Leaf(56.78)), | |
); | |
println!("weight: {}", tree_float.tree_weight()); | |
tree_float.traverse(&print_payload::<f32>); | |
let tree_string = BinaryTree::Branch( | |
Box::new(BinaryTree::Leaf(String::from("abc"))), | |
String::from("def"), | |
Box::new(BinaryTree::Leaf(String::from("ghi"))), | |
); | |
// won't compile: println!("weight: {}", tree_string.tree_weight()); | |
tree_string.traverse(&print_payload::<String>); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment