gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:43:18 24 4
gpt4 key购买 nike

我正在尝试实现一个返回递归闭包的函数,尽管我不确定如何在函数签名中表达它。以下是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com