Search code examples
rascal

Write even shorter visits


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;
  }
};

Solution

  • 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.