Guest User

Untitled

a guest
Dec 9th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. #[derive(Debug, Clone)]
  2. pub enum Expr {
  3. BinOp(char, Box<Expr>, Box<Expr>),
  4. Pow(Box<Expr>, Box<Expr>),
  5. Neg(Box<Expr>),
  6. Function(char, Box<Expr>),
  7. Constant(f64),
  8. Identifier(String),
  9. }
  10.  
  11. impl Expr {
  12. // returns `self` and all children in vec (using `self.items_as_vec()`)
  13. /// 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`.
  14. pub fn as_vec(&mut self) -> Vec<&mut Expr> {
  15. let mut items = Vec::<&mut Expr>::new();
  16. items.push(self);
  17. items.extend(self.items_as_vec());
  18. items
  19. }
  20.  
  21. // will not return `self`, but includes all children in vec
  22. /// Returns a `Vec` of all `self`'s children, and their children, and so on. Children are any items that are of type `Expr`.
  23. pub fn items_as_vec(&mut self) -> Vec<&mut Expr> {
  24. let mut items = Vec::<&mut Expr>::new();
  25. match self {
  26. Expr::BinOp(_, a, b) => {
  27. items.push(a);
  28. items.extend(a.items_as_vec());
  29. items.push(b);
  30. items.extend(b.items_as_vec());
  31. }
  32. Expr::Pow(a, b) => {
  33. items.push(a);
  34. items.extend(a.items_as_vec());
  35. items.push(b);
  36. items.extend(b.items_as_vec());
  37. }
  38. Expr::Neg(a) => {
  39. items.push(a);
  40. items.extend(a.items_as_vec());
  41. }
  42. Expr::Function(_, a) => {
  43. items.push(a);
  44. items.extend(a.items_as_vec());
  45. }
  46. _ => {}
  47. }
  48. items
  49. }
  50. }
  51.  
  52. fn main() {
  53. let ast = Expr::Constant(20.);
  54. println!("{:?}", ast.as_vec()); // [Constant(20.0)]
  55. }
Add Comment
Please, Sign In to add comment