rust - Passing a closure to a recursive function -


i'm working on quad tree. using closure determine when region should split seems idea.

pub fn split_recursively(&mut self, f: |rect| -> bool) {     ...     self.children.as_mut().map(|children| {         children.nw.split_recursively(f);         children.ne.split_recursively(f);         children.sw.split_recursively(f);         children.se.split_recursively(f);     }); } 

the above have tried, get

error: cannot move out of captured outer variable

children.se.split_recursively(f);

                      ^ 

for each of 4 children.

i tried wrapping closure in refcell

fn split_recursively(&mut self, f: &refcell<|rect| -> bool>) 

and calling it

let should_split = (*f.borrow_mut())(self.rect); 

but rust doesn't either:

error: closure invocation in & reference

i know how work around passing function pointer , &mut rng (because splitting should in part depend on randomness), closure more elegant. there way work closure? if not, possible unboxed closures?

unboxed closures work feature-gated , add complexity.

#![feature(unboxed_closures)] use std::ops::fn;  fn main() {     let f = |&: x: uint| println!("recurse {}!", x);      recursive(&f, 0); }  fn recursive(f: &fn<(uint,), ()>, depth: uint) {     if depth < 10 {         f.call((depth,)); // cannot invoked f(depth) currently.         recursive(f, depth + 1);     } else {         ()     } } 

(rust-playpen link)

searching around, found easy solution. call closure in closure:

fn main() {     let f = |x: uint| println!("recurse {}!", x);      recursive(f, 0); }  fn recursive(f: |uint| -> (), depth: uint) {     if depth < 10 {         f(depth);         recursive(|x| f(x), depth + 1);     } else {         ()     } } 

(rust-playpen link)

this has performance impact compared unboxed closures it's easier read. choice.


Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -