Unable to translate vector of vector or item from python to rust

I am trying to translate the following program, which groups items by parenthesis from python to rust:

stack = [[]]

program = [x for x in "a+(b(c+d)+e+(f+(g)))"]

for token in program:
    if token == "(":
        stack.append([])
    elif token == ")":
        popped = stack.pop(); stack[-1].append(popped)
    else:
        stack[-1].append(token)

print(stack[0])
enum TokenTree {
    Parens(Vec<TokenTree>),
    Token(char),
}
use TokenTree::*;
impl std::fmt::Debug for TokenTree {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Parens(list) => list.fmt(f),
            Token(c) => c.fmt(f),
        }
    }
}

fn main() {
    let mut stack = vec![vec![]];
    let program = "a+(b(c+d)+e+(f+(g)))".chars();
    for token in program {
        match token {
            '(' => stack.push(vec![]),
            ')' => {
                let popped = stack.pop().unwrap();
                stack.last_mut().unwrap().push(Parens(popped));
            }
            _ => stack.last_mut().unwrap().push(Token(token)),
        }
    }
    println!("{:?}", stack[0]);
}

Rust Playground

Or you could also derive the Debug implementation if you don't care about getting the exact same output as the python program.

(I wrote this answer on mobile, so haven't added much explanation.)

1 Like

Oh, I had the exact same code, but I didn't know about last_mut, so I have tried every possible combination of adding & and but, but to no avail. Thank you so very much!

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.