#how can i put an element back in an iterator?

9 messages · Page 1 of 1 (latest)

stark ore
#

tried asking ChatGPT but was no help. the question is how can i put an element back in an iterator? specifically a Peekable<Chars>.
here is the necessary code. its for a parser im writing. if a minus i followed by a number it should continue parsing the rest of the number, if else it should put the minus back in self.code and return Ok(()) to indicate that its done trying to parse a number.

Some('-') => {
    num_string.push(self.code.next().unwrap());
    if let Some('0'..='9') = self.code.peek() {
    } else {
        // put minus back on the in the code
        return Ok(())
    }
}
vagrant prism
#

Iterators don't contain elements in the first place, the notion of putting them back doesn't really make sense.

#

Bright side is, you may not need this for your code.

#

The idea is to peek elements until you're absolutely sure they can be nexted

stark ore
#

but you can only peek the first element, right? unless im missing something

vagrant prism
#

You can, yeah. If you want to do more you may want to keep a vector and a "current element" usize index.

Or use itertools' multipeek

keen anchor
#

Peek only stores one item, and it only stores items of the same type as the iterator. For something like this you'd want to store state separately from the iterator so you can store whatever you want, such as "this was preceded by a minus" or "there's a number being read"

stark ore
#
Some('-') => {
    let mut code_copy = self.code.clone();
    code_copy.next();
    if let Some('0'..='9') = code_copy.peek() {
        num_string.push(self.code.next().unwrap());
    } else {
        return self.parse_word()
    }
}

ok i realize that this is a kinda dumb way of doing it but how dumb is it?