Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. pub struct Expr(pub Vec<Box<ExprItem>>);
  2.  
  3. pub enum ExprItem {
  4. Word(String),
  5. Candidates(Vec<Box<Expr>>),
  6. }
  7.  
  8. pub fn expand(expr: &Expr, idx: usize, stack: &mut Vec<String>, callback: &Fn(&mut Vec<String>))
  9. {
  10. if idx == expr.0.len() {
  11. callback(stack);
  12. return;
  13. }
  14. let item: &ExprItem = &expr.0[idx];
  15. match *item {
  16. ExprItem::Word(ref val) => {
  17. stack.push(val.to_owned());
  18. expand(expr, idx + 1, stack, callback);
  19. stack.pop();
  20. }
  21. ExprItem::Candidates(ref candidates) => {
  22. if candidates.is_empty() {
  23. expand(expr, idx + 1, stack, callback);
  24. } else {
  25. for candidate in candidates {
  26. expand(&candidate, 0, stack, &|res| {
  27. expand(expr, idx + 1, res, callback);
  28. });
  29. }
  30. }
  31. }
  32. }
  33. }
  34.  
  35. fn main() {
  36. let expr = Expr(vec![
  37. Box::new(ExprItem::Word("hello".to_owned())),
  38. Box::new(ExprItem::Candidates(vec![
  39. Box::new(
  40. Expr(vec![Box::new(ExprItem::Word("a".to_owned()))])
  41. ),
  42. Box::new(
  43. Expr(vec![Box::new(ExprItem::Word("b".to_owned()))])
  44. ),
  45. ])),
  46. Box::new(ExprItem::Candidates(vec![
  47. Box::new(
  48. Expr(vec![Box::new(ExprItem::Word("c".to_owned()))])
  49. ),
  50. Box::new(
  51. Expr(vec![Box::new(ExprItem::Word("d".to_owned()))])
  52. ),
  53. ])),
  54. Box::new(ExprItem::Candidates(vec![])),
  55. Box::new(ExprItem::Word("world".to_owned())),
  56. ]);
  57. let mut stack = Vec::new();
  58. expand(&expr, 0, &mut stack, &|res: &mut Vec<String>| {
  59. println!("{}", res.join("-"));
  60. });
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement