Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #[derive(Debug, Clone)]
- pub enum Expr {
- BinOp(char, Box<Expr>, Box<Expr>),
- Pow(Box<Expr>, Box<Expr>),
- Neg(Box<Expr>),
- Function(char, Box<Expr>),
- Constant(f64),
- Identifier(String),
- }
- impl Expr {
- // returns `self` and all children in vec (using `self.items_as_vec()`)
- /// Returns a `Vec` of all `Expr` in `self`. This will include `self`, and all of `self`'s children, and their children, and so on. Children are any items that are of type `Expr`.
- pub fn as_vec(&mut self) -> Vec<&mut Expr> {
- let mut items = Vec::<&mut Expr>::new();
- items.push(self);
- items.extend(self.items_as_vec());
- items
- }
- // will not return `self`, but includes all children in vec
- /// Returns a `Vec` of all `self`'s children, and their children, and so on. Children are any items that are of type `Expr`.
- pub fn items_as_vec(&mut self) -> Vec<&mut Expr> {
- let mut items = Vec::<&mut Expr>::new();
- match self {
- Expr::BinOp(_, a, b) => {
- items.push(a);
- items.extend(a.items_as_vec());
- items.push(b);
- items.extend(b.items_as_vec());
- }
- Expr::Pow(a, b) => {
- items.push(a);
- items.extend(a.items_as_vec());
- items.push(b);
- items.extend(b.items_as_vec());
- }
- Expr::Neg(a) => {
- items.push(a);
- items.extend(a.items_as_vec());
- }
- Expr::Function(_, a) => {
- items.push(a);
- items.extend(a.items_as_vec());
- }
- _ => {}
- }
- items
- }
- }
- fn main() {
- let ast = Expr::Constant(20.);
- println!("{:?}", ast.as_vec()); // [Constant(20.0)]
- }
Add Comment
Please, Sign In to add comment