Building function closures out of function closures

Is it possible for a recursive function to build up a function closure and return it to the caller? Basically the recursive function will take an initial lambda function and it will add one more closure(with each function call of the recursive function) that calls the previous closure and so on until it reaches the initial lambda function.

Is this possible in Rust and can someone show me a simple example of this?

Sure, you just need to box the closure at each level.

// returns a closure that adds n to a number
fn add_n(n: u32) -> Box<dyn Fn(u32) -> u32> {
    if n == 0 {
        Box::new(|i| i)
    } else {
        let inner = add_n(n - 1);
        // the move keyword transfers ownership of inner into the new closure
        Box::new(move |i| inner(i) + 1)
    }
}

playground

3 Likes

Now I just have to apply that to the Btree function I'm working on. Thanks.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.