我正在尝试扁平化递归结构,但在使用递归迭代器时遇到了麻烦。
结构如下:
#[derive(Debug, Clone)]
pub struct C {
name: String,
vb: Option<Vec<B>>,
}
#[derive(Debug, Clone)]
pub struct B {
c: Option<C>,
}
#[derive(Debug, Clone)]
pub struct A {
vb: Option<Vec<B>>,
flat_c: Option<Vec<C>>,
}
我的计划是遍历vb
向量并将其展平为flat_c
。我希望它看起来像这样,或者至少是Vec<String>
:
Some([
C {
name: "foo",
vb: None,
},
C {
name: "bar",
vb: None,
},
C {
name: "fizz",
vb: None,
},
C {
name: "buzz",
vb: None,
},
])
这是我设法完成的工作,虽然没有实现递归,但是使结构稍微平坦了,但仅针对最后一个元素。
impl A {
fn flat_c(self) -> Self {
let fc: Vec<C> = self
.vb
.clone()
.unwrap()
.iter()
.flat_map(|x| x.c.as_ref().unwrap().vb.as_ref().unwrap().iter())
.cloned()
.map(|x| x.c.unwrap())
.collect();
Self {
flat_c: Some(fc),
..self
}
}
}
fn main() {
let a = A {
vb: Some(vec![
B {
c: Some(C {
name: "foo".to_string(),
vb: Some(vec![B {
c: Some(C {
name: "bar".to_string(),
vb: None,
}),
}]),
}),
},
B {
c: Some(C {
name: "fiz".to_string(),
vb: Some(vec![B {
c: Some(C {
name: "buzz".to_string(),
vb: None,
}),
}]),
}),
},
]),
flat_c: None,
};
let a = a.flat_c();
println!("a: {:#?}", a);
}
flat_c
的输出:
Some([
C {
name: "bar",
vb: None,
},
C {
name: "buzz",
vb: None,
},
])
我还没有深入研究此问题可能需要的Iterator
特征实现。
我将如何解决这个问题?也许使用fold
?也许甚至不需要递归方法?我很茫然。
答案 0 :(得分:3)
熟悉常见的数据结构是一个好主意。您有一个tree,并且有几种方法to traverse a tree。您尚未精确指定要使用的方法,因此我任意选择了一种易于实现的方法。
这里的关键是实现一个跟踪某些状态的迭代器:所有尚未访问的节点。在每次调用Iterator::next
时,我们都会获取下一个值,将要访问的所有新节点保存在一边,然后返回该值。
一旦有了迭代器,就可以将其collect
变成Vec
。
use std::collections::VecDeque;
impl IntoIterator for A {
type IntoIter = IntoIter;
type Item = String;
fn into_iter(self) -> Self::IntoIter {
IntoIter {
remaining: self.vb.into_iter().flatten().collect(),
}
}
}
struct IntoIter {
remaining: VecDeque<B>,
}
impl Iterator for IntoIter {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
self.remaining.pop_front().and_then(|b| {
b.c.map(|C { name, vb }| {
self.remaining.extend(vb.into_iter().flatten());
name
})
})
}
}
fn to_strings(a: A) -> Vec<String> {
a.into_iter().collect()
}
#[derive(Debug, Clone)]
struct A {
vb: Option<Vec<B>>,
}
#[derive(Debug, Clone)]
struct B {
c: Option<C>,
}
#[derive(Debug, Clone)]
struct C {
name: String,
vb: Option<Vec<B>>,
}
如果需要的话,从这里开始,直接创建B
的迭代器。拥有所有None
值似乎很愚蠢,因此我将它们排除在外,直接返回了String
。
我也将其设为按值迭代器。您可以遵循相同的模式来创建迭代器,该迭代器返回对B
/ String
的引用,并仅在需要时将其克隆。
另请参阅:
答案 1 :(得分:1)
有我的解决方案:
impl C {
fn flat(&self) -> Vec<C> {
let mut result = Vec::new();
result.push(C {
name: self.name.clone(),
vb: None,
});
if self.vb.is_some() {
result.extend(
(self.vb.as_ref().unwrap().iter())
.flat_map(|b| b.c.as_ref().map(|c| c.flat()).unwrap_or(Vec::new())),
);
}
return result;
}
}
impl A {
fn flat_c(self) -> Self {
let fc = (self.vb.as_ref().unwrap().iter())
.flat_map(|b| b.c.as_ref().unwrap().flat())
.collect();
Self {
flat_c: Some(fc),
..self
}
}
}
它为flat
添加了C
函数,因为C
是递归的源,只有该结构才能正确处理它。
由于这些Option
,它看起来很恐怖,很难处理隐秘的错误消息。此解决方案假定开头b.c
的所有a
都不是None
。否则,会惊慌。我的建议是避免使用Option<Vec>
,而只使用空向量而不是None
。
答案 2 :(得分:0)
我不确定您到底希望“遍历vb
向量并将其展平为flat_c
”的结果到底是什么,但这是一个使用递归结构展平的简单示例once
表示与当前节点相对应的值,chain
将其与其子级连接起来,flat_map
则将所有内容展平:
use std::iter::once;
#[derive(Debug)]
struct S {
name: String,
children: Vec<S>,
}
impl S {
fn flat(self) -> Vec<String> {
once(self.name)
.chain(self.children.into_iter().flat_map(|c| c.flat()))
.collect()
}
}
fn main() {
let s = S {
name: "parent".into(),
children: vec![
S {
name: "child 1".into(),
children: vec![],
},
S {
name: "child 2".into(),
children: vec![],
},
],
};
println!("s: {:?}", s);
println!("flat: {:?}", s.flat());
}