0

Say I have a data type defined as follows:

data Constraint=type1(Lab al,Lab a2)| type2(Lab a1,TypeRoot tt)|....

where the general pattern is that the first argument of each constructor is of type 'Lab'. Is there then, an efficient/clear way of expressing a pattern match to do the following?

for (Constraint cc <- constraints)
    if( type1(Lab label,_):= cc || type2(Lab label,_):=cc || .... )
        //do something useful with label. Infact, this snippet of code appears within
        //a function body, and I need to perform the match for a specific label; as follows:
        if(label==labelOfInterest) return cc;

While I'm at this, and against StackOverflow's recommendation of asking one question/thread, does Rascal support simple Java-like recursions?

apil.tamang
  • 2,545
  • 7
  • 29
  • 40
  • Rascal does support recursion. If you post a more complete example of what you are trying to recurse over that would help. – Mark Hills Nov 16 '14 at 22:21
  • Have a look at the factorial example: http://tutor.rascal-mpl.org/Recipes/Recipes.html#/Recipes/Basic/Factorial/Factorial.html – Jurgen Vinju Nov 17 '14 at 09:32
  • and for recursion you should not skip the `visit` statement: http://tutor.rascal-mpl.org/Rascal/Rascal.html#/Rascal/Expressions/Visit/Visit.html – Jurgen Vinju Nov 17 '14 at 09:33

1 Answers1

1

You can check for the presence of a field by way of the has operator. See the Rascal Tutor for details.

Your code would then become something like:

for (Constraint cc <- constraints)
    if( cc has a1 || .... )
        if(cc.label==labelOfInterest) return cc;

or even better:

for (Constraint cc <- constraints)
    if( (cc has a1 && cc.label == labelOfInterest) || .... )
        return cc;
Paul Klint
  • 1,418
  • 7
  • 12
  • Or even `for (Constraint cc <- constraints, cc has a1, cc.a1 == labelOfInterest)` – Mark Hills Nov 16 '14 at 22:20
  • do you both mean, "cc has Lab" instead of "cc has a1", since a1 is just an arbritrary name of the argument? Shouldn't the more significant pattern identifier be the type of the argument, i.e. "Lab" instead of the name of the argument, i.e. "a1" ? – apil.tamang Nov 16 '14 at 22:43
  • It's the name of the label which counts. There could be two labels of the same type after all. The type is just for type checking, the label is where the data really is stored under (so much more significant). – Jurgen Vinju Nov 17 '14 at 09:31