Created
April 19, 2015 02:48
-
-
Save mwhittaker/b46c04e120dca634bd6e to your computer and use it in GitHub Desktop.
Rust Tree Fold
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
use Tree::{Leaf, Node}; | |
enum Tree<A> { | |
Leaf, | |
Node(Box<Tree<A>>, A, Box<Tree<A>>) | |
} | |
fn tree_fold<A, B, F>(f: &F, a: B, t: &Tree<A>) -> B where F: Fn(B, &A, B) -> B, B: Clone { | |
match *t { | |
Leaf => a, | |
Node(ref l, ref x, ref r) => { | |
let l = tree_fold(f, a.clone(), l); | |
let r = tree_fold(f, a.clone(), r); | |
f(l, x, r) | |
} | |
} | |
} | |
fn main() { | |
let l = Node(Box::new(Leaf), 1, Box::new(Leaf)); | |
let r = Node(Box::new(Leaf), 3, Box::new(Leaf)); | |
let t = Node(Box::new(l), 2, Box::new(r)); | |
println!("{}", tree_fold(&|l, &x, r| l + x + r, 0, &t)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment