Skip to content

Instantly share code, notes, and snippets.

@mwhittaker
Created April 19, 2015 02:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwhittaker/b46c04e120dca634bd6e to your computer and use it in GitHub Desktop.
Save mwhittaker/b46c04e120dca634bd6e to your computer and use it in GitHub Desktop.
Rust Tree Fold
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