【问题标题】:More techniques for recursive patterns in iteration迭代中递归模式的更多技术
【发布时间】: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


    【解决方案1】:

    你所说的模式是一个“状态机”,在 Rust 中最好使用枚举来表示:

    enum Frame {
        NextStates(NextStatesIterator, State),
        OtherStates(OtherStatesIterator)
    }
    struct Iterator {
        stack: Vec<Frame>, 
    }
    

    【讨论】:

    • 我想我正在努力解决的问题是在这种情况下如何为迭代器编写惯用的程序代码;您如何简洁明了地表示程序流程?由于有多个返回点,因此快速管理细节变得非常具有挑战性。
    猜你喜欢
    • 2015-07-11
    • 2020-08-28
    • 2010-10-05
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    • 2012-10-17
    • 2019-12-10
    相关资源
    最近更新 更多