返回递归闭包的函数签名

11

我正在尝试实现一个返回递归闭包的函数,但是我不确定如何在函数签名中表达这一点。以下是Python中可工作实现的示例代码:

def counter(state):
    def handler(msg):
        if msg == 'inc':
            print state
            return counter(state + 1)

        if msg == 'dec':
            print state
            return counter(state - 1)
    return handler

c = counter(1)
for x in range(1000000):
    c = c('inc')

以及Rust的伪代码。

enum Msg {
    Inc,
    Dec
}

fn counter(state: Int) -> ? {
    move |msg| match msg {
        Msg::Inc => counter(state + 1),
        Msg::Dec => counter(state - 1),
    }
}
1个回答

11
因为Rust支持递归类型,所以您只需要将递归编码到一个单独的结构中:

由于Rust支持递归类型,因此您只需在一个单独的结构中编码递归:

enum Msg { 
    Inc,
    Dec,
}

// in this particular example Fn(Msg) -> F should work as well
struct F(Box<FnMut(Msg) -> F>);

fn counter(state: i32) -> F {
    F(Box::new(move |msg| match msg {
        Msg::Inc => {
            println!("{}", state);
            counter(state + 1)
        }
        Msg::Dec => {
            println!("{}", state);
            counter(state - 1)
        }
    }))
}

fn main() {
    let mut c = counter(1);
    for _ in 0..1000 {
        c = c.0(Msg::Inc);
    }
}

很不幸,我们不能在这里取消装箱 - 因为非装箱闭包具有无法命名的类型,所以我们需要将它们装箱成trait对象才能在结构声明中命名它们。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接