2

Is it possible to rewrite a visit like this to a single line by using a list comprehension or something similar?

list[str] nodeNames = [];

visit (ast) {
  case someNode(str name): {
    nodeNames += name;
  }
};
Nicasso
  • 265
  • 1
  • 7

1 Answers1

5

Yes you can using what we call the descendant match operator /:

[name | /someNode(str name) := ast];

You see here

  • a list comprehension between [ and ].
  • a match operator := with a pattern on the left and a subject on the right.
  • a descendant pattern /someNode(str name) that will match every subnode of the form someNode(str name) and will bind pattern variable name.

The overall effect is the same as your formulation using visit: all name fields from someNodes are collected and placed in a list. This the shortest possible solution for your problem.

Paul Klint
  • 1,418
  • 7
  • 12