Advertisement
Guest User

Untitled

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