Skip to main content

Insert

rascal-0.28.2

Synopsis

Insert a value in a tree during a Visit.

Syntax

insert Exp;

Description

An insert statement may only occur in the action part of a ./Pattern With Action, more precisely in a case in a Visit expression. The value matched by the pattern of this case is replaced by the value of Exp.

The following rule applies:

  • The static type of Exp should be a subtype of the type of the value that is replaced.

Examples

Consider the following datatype CTree and assign a CTree value to variable T:

rascal>data CTree = leaf(int n) | red(CTree left, CTree right) | green(CTree left, CTree right);
ok
rascal>CTree T = red(green(leaf(1), red(leaf(2), leaf(3))), red(leaf(4), leaf(5)));
CTree: red(
green(
leaf(1),
red(
leaf(2),
leaf(3))),
red(
leaf(4),
leaf(5)))

We can now switch the arguments of all red nodes as follows:

rascal>visit(T){
>>>>>>> case red(CTree l, CTree r): insert red(r,l);
>>>>>>>}
CTree: red(
red(
leaf(5),
leaf(4)),
green(
leaf(1),
red(
leaf(3),
leaf(2))))

Since this is a very common idiom, we also have a shorthand for it:

rascal>visit(T){
>>>>>>> case red(CTree l, CTree r) => red(r,l)
>>>>>>>}
CTree: red(
red(
leaf(5),
leaf(4)),
green(
leaf(1),
red(
leaf(3),
leaf(2))))

Pitfalls

There is a glitch in the Rascal syntax that requires a semicolon after a case (as in the first example), but refuses it in the abbreviated version using => (the second example).