post-tree

Dec. 24th, 2022 04:12 pm
amarao: (Default)
[personal profile] amarao
Интернеты говорят, что во-первых Rc<RefCell> не идиоматично для Rust (деревья правильно держать как банальные вектора, содержащие в себе вектора векторов). Во-вторых, я, в целом, всё правильно сделал.

После некоторого кумекания получилось вот так вот, и я не вижу как его сделать существенно компактнее. Может быть, можно уйти от Enum и бального true/false хватит?

Да, получилось.

fn mktree(source: &[Option<i32>]) -> Tree {
if source.is_empty() || source[0].is_none() {
return None;
}
let tree: Tree = new_tree(source[0].unwrap());
let mut buff = VecDeque::new();
buff.push_back((tree.as_ref().cloned(), false));
for val in source[1..].into_iter() {
let subtree = val.and_then(|val| {
let subtree = new_tree(val);
buff.push_back((subtree.as_ref().cloned(), false));
subtree
});
let (node, is_last) = buff.pop_front().unwrap();
if is_last {
node.unwrap().borrow_mut().right = subtree;
} else {
node.as_ref().unwrap().borrow_mut().left = subtree;
buff.push_front((node.as_ref().cloned(), true));
}
}
tree
}

Что меня смущает? Изобилие as_ref().cloned(). Ща буду думать...
This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

Profile

amarao: (Default)
amarao

April 2026

S M T W T F S
   1234
567 891011
12131415161718
19202122232425
2627282930  

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Apr. 12th, 2026 09:39 am
Powered by Dreamwidth Studios