recursion - 返回递归闭包的函数签名

标签 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),
    }
}

最佳答案

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

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

关于recursion - 返回递归闭包的函数签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35832419/

相关文章:

javascript - 在闭包内调用类函数 React native

java - 斐波那契数列 - 递归求和

delphi - 如何声明包含使用记录作为参数的事件的记录

c++ - 递归函数中迭代器的段错误

c# - 如何检查ArrayList中对象的类型

c++ - 对于 const 的引用,std::is_const 的等价物是什么?

javascript - Mithril 组件组合中单独单击增量按钮

javascript - 这是闭包在 useState 钩子(Hook)中的工作方式吗?

java - 使用递归选择团队

parsing - 跳出深度递归函数调用