My goal is to find all minimal subspaces of boolean variables satisfying a condition. I already have a way to find all subspaces with the condition, and I need to extract only the minimal ones. The idea is to iterate over them ordered by increasing size and remove all greater ones at every iteration, which can be done efficiently, so it would hopefully exponentially reduce the number of iterations compared to if I didn’t delete them.
How can I do that? I have seen solutions to an iterator where the references iterated over are mutable (slice::IterMut), but this is different because I want to change the shape of the structure over which it is iterated, not its individual elements. The only thing happening to individual elements is that they would be deleted.
Minimal reproducible example
I redid the iterator for a set of numbers because my original data structure is too complex for a reproducible example.
use std::collections::BTreeSet;
pub struct MutIterator<'a> {
base: &'a mut BTreeSet<i32>,
state: Option<i32> }
impl MutIterator<'_> {
pub fn new(base: &mut BTreeSet<i32>) -> MutIterator {
let state = base.first().map(i32::clone);
MutIterator {
base,
state } } }
impl<'a> Iterator for MutIterator<'a> {
type Item = i32;
fn next(&mut self) -> Option<Self::Item> {
let result = self.state;
self.state = match self.state {
Some(x) => {
Some(self.base.range(x+1..).next()?.clone()) }
None => None };
result } }
fn example() {
let mut set = BTreeSet::from_iter(1..100);
let mut_it = MutIterator::new(&mut set);
for element in mut_it {
set = &set - &BTreeSet::from([element * 2]) } } }
If I try to compile it, it complains about the last line so:
cannot assign to
set
because it is borrowed [E0506]
cannot borrow
set
as immutable because it is also borrowed as mutable [E0502]
I haven’t figured out how to solve that. I know why the errors are there, but I don’t know a solution which would avoid them, although the operations don’t do anything which would break Rust’s memory safety AFAIK. Do I need to use an unsafe
block for this, or how do I solve that?
8