Domanda

I want to create a tree (using a Node or ADT) in which every node has an annotation pointing back to its parent. Below is an example with a simple linked list data structure:

import util::Math;
import IO;
import Node;

anno LinkedList LinkedList@parent;
anno int LinkedList@something;

data LinkedList = item(int val, LinkedList next)
                | last(int val)
                ;

public LinkedList linkedList =  item(5,
                                    item(4,
                                        item(3,
                                            item(2,
                                                last(1)[@something=99]
                                            )[@something=99]
                                        )[@something=99]
                                    )[@something=99]
                                )[@something=99];

public LinkedList addParentAnnotations(LinkedList n) {
    return top-down visit (n) {
        case LinkedList x: {
            /* go through all children whose type is LinkedList */
            for (LinkedList cx <- getChildren(x), LinkedList ll := cx) {
                /* setting the annotation like this doesn't seem to work */
                cx@parent = x;
                // DOESN'T WORK EITHER: setAnnotation(cx, getAnnotations(cx) + ("parent": x));
            }
        }
    }
}

Executing addParentAnnotations(linkedList) yields the following result:

rascal>addParentAnnotations(linkedList);
LinkedList: item(
  5,
  item(
    4,
    item(
      3,
      item(
        2,
        last(1)[
          @something=99
        ])[
        @something=99
      ])[
      @something=99
    ])[
    @something=99
  ])[
  @something=99
]
È stato utile?

Soluzione

The thing is that Rascal data is immutable, so you can not update anything using an assignment. The assignment will simply give you a new binding for cx with the annotation set, but will not change the original tree.

To change the original tree, you can either use the => operator for case statements, or the insert statement as follows:

 case LinkedList x => x[@parent=...] // replace x by a new x that is annotated

or:

 case LinkedList x : {
    ...
    x@parent= ...;
    insert x; // replace original x by new x in tree
 }

Some other tip, in the Traversal.rsc library you can find a function called getTraversalContext() which produces a list of parents of the currently visited node if called from the body of a case:

import Traversal;

visit (...) {
    case somePattern: {
        parents = getTraversalContext();
        parent = parents[1];
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top