Safely remove return statement?

Context: scryer-prolog/iterators.rs at l0_final · mthom/scryer-prolog · GitHub

impl<'a> Iterator for BreadthFirstIterator<'a> {
    type Item = &'a Term;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(term) = self.state_queue.pop_front() {            
            if let &Term::Clause(_, _, ref child_terms) = term {
                for term in child_terms {
                    self.state_queue.push_back(term);
                }

                return Some(term); // <-- THIS LINE
            }

            return Some(term);
        }

        None
    }
}

Can THIS LINE be safely removed ? Intuitively, I think yes, but I am trying to figure out if there is some Rust / Prolog / WAM black magic that is throwing me off.

Should be safe, yes. It would only be problematic if in the inner return, the variable term would be referring to something else, e. g. due to shadowing.

1 Like

But it is not happening right?

        if let Some(term) = self.state_queue.pop_front() {            
            if let &Term::Clause(_, _, ref child_terms) = term {
                for term in child_terms { // LINE A
                    self.state_queue.push_back(term);
                } // LINE B

                return Some(term); // <-- THIS LINE
            }

            return Some(term);
        }

The only other place where term is redefined is Line A, but that goes out of scope at Line B.

Yes, correct.

1 Like

One could go further with the rewriting and do something like

let next_term = .... pop_front();
if let Some(Term::Clause(_, _, child_terms)) = &next_term {
   for term in ....
}
next_term
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.