Skip to content

Instantly share code, notes, and snippets.

Created January 30, 2017 12:49
Show Gist options
  • Save anonymous/6f1335809d1c642f16f5a9e71d1c978e to your computer and use it in GitHub Desktop.
Save anonymous/6f1335809d1c642f16f5a9e71d1c978e to your computer and use it in GitHub Desktop.
enum Token {
Start,
End,
Value(i32),
}
enum Node {
List(Vec<Node>),
Value(i32),
}
fn main() {
let v = vec![Token::Start, Token::Value(1), Token::End];
parse(&v);
}
fn parse(tokens: &Vec<Token>) -> Node {
let mut root: Vec<Node> = vec![];
{
tokens.into_iter().fold(vec![&mut root], handle_token);
}
Node::List(root)
}
fn handle_token<'a>(mut stack: Vec<&'a mut Vec<Node>>, token: &Token) -> Vec<&'a mut Vec<Node>> {
match *token {
Token::Start => {
stack[0].push(Node::List(vec![])); // Add the new node to the tree
match stack[0][0] {
Node::List(ref mut the_vec) => stack.push(the_vec), // Add a mutable reference to the new vector so that subsequent nodes will become children of this Node
_ => panic!(),
};
},
Token::End => { stack.pop(); },
Token::Value(v) => stack[0].push(Node::Value(v)),
}
stack
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment