How to define mutual recursion with closures?

前端 未结 2 1924
甜味超标
甜味超标 2021-01-20 23:18

I can do something like this:

fn func() -> (Vec, Vec) {
    let mut u = vec![0;5];
    let mut v = vec![0;5];

    fn foo(u: &mut [i         


        
2条回答
  •  误落风尘
    2021-01-20 23:56

    I have a solution for mutually recursive closures, but it doesn't work with multiple mutable borrows, so I couldn't extend it to your example.

    There is a way to use define mutually recursive closures, using an approach similar to how this answer does single recursion. You can put the closures together into a struct, where each of them takes a borrow of that struct as an extra argument.

    fn func(n: u32) -> bool {
        struct EvenOdd<'a> {
            even: &'a Fn(u32, &EvenOdd<'a>) -> bool,
            odd: &'a Fn(u32, &EvenOdd<'a>) -> bool
        }
        let evenodd = EvenOdd {
            even: &|n, evenodd| {
                if n == 0 {
                    true
                } else {
                    (evenodd.odd)(n - 1, evenodd)
                }
            },
            odd: &|n, evenodd| {
                if n == 0 {
                    false
                } else {
                    (evenodd.even)(n - 1, evenodd)
                }
            }
        };
        (evenodd.even)(n, &evenodd)
    }
    
    fn main() {
        println!("{}", func(5));
        println!("{}", func(6));
    }
    

提交回复
热议问题