【发布时间】:2020-10-31 16:54:14
【问题描述】:
在Techniques for turning recursive functions into iterators in Rust? 的基础上,我想探索迭代器的挑战。
让我们考虑一个基于收益的递归函数,它的控制流程稍微复杂一些:
function one_level(state, depth, max_depth) {
if depth == max_depth {
return
}
if external_condition(state) { // location-1
for s in next_states_from(state) { // loop-1
yield state_to_value(s);
yield one_level(s, depth+1, max_depth);
}
} else {
for s in other_next_state_from(state) { // loop-2
yield one_level(s, depth+1, max_depth) // location-2
}
}
}
这里的事情变得有趣了,因为有:
- 条件分支
- 多个递归点
在 Rust 迭代器中管理所有这些,我发现自己基本上用 location_1_reached:bool 之类的属性来装饰我的状态对象,这样我就可以在返回之前在我的 next() 函数中设置这些。然后我需要用检查乱扔我的代码,看看我们上次通过这个堆栈帧的状态走了多远。同样,我正在努力以一种干净的方式处理这个问题。
我对建议最感兴趣。作为对我的痛苦的暗示,这是我为今天的工作而定义的那种结构:
struct MyIteratorStackFrame<'a> {
arg_1: usize,
arg_2: Point,
loop_1_values: Box<dyn Iterator<Item = &'a State> + 'a>,
loop_2_values: Box<dyn Iterator<Item = &'a State> + 'a>,
location_1_reached: bool,
location_2_reached: bool
}
struct MyIterator<'a> {
max_depth: usize,
stack: Vec<MyIteratorStackFrame<'a>>,
}
【问题讨论】:
标签: recursion rust iterator iteration state