用于返回递归闭包的函数签名

时间:2016-03-06 20:54:07

标签: recursion types closures rust continuations

我试图实现一个返回递归闭包的函数。虽然我不知道如何在函数签名中表达它。以下是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 个答案:

答案 0 :(得分:11)

因为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);
    }
}

不幸的是,我们无法取消拳击 - 因为未装箱的闭包具有不可命名的类型,我们需要将它们装入特征对象,以便能够在结构声明中命名它们。