返回递归闭包的函数签名
Function signature for returning a recursive closure
我正在尝试实现一个 returns 递归闭包的函数,尽管我不确定如何在函数签名中表达它。这是 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);
}
}
不幸的是,我们不能在这里取消装箱 - 因为未装箱的闭包具有不可命名的类型,我们需要将它们装箱到特征对象中以便能够在结构声明中命名它们。
我正在尝试实现一个 returns 递归闭包的函数,尽管我不确定如何在函数签名中表达它。这是 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);
}
}
不幸的是,我们不能在这里取消装箱 - 因为未装箱的闭包具有不可命名的类型,我们需要将它们装箱到特征对象中以便能够在结构声明中命名它们。