3

我想创建一个树(使用Nodeor ADT),其中每个节点都有一个指向其父节点的注释。下面是一个简单的链表数据结构的例子:

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

执行addParentAnnotations(linkedList)产生以下结果:

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

1 回答 1

3

问题是 Rascal 数据是不可变的,因此您无法使用分配更新任何内容。分配只会为您提供cx与注释集的新绑定,但不会更改原始树。

要更改原始树,您可以使用=>运算符 for case 语句,也可以使用insert如下语句:

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

或者:

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

其他一些提示,在Traversal.rsc库中,您可以找到一个调用的函数getTraversalContext(),如果从案例主体调用,该函数会生成当前访问节点的父节点列表:

import Traversal;

visit (...) {
    case somePattern: {
        parents = getTraversalContext();
        parent = parents[1];
    }
}
于 2013-09-26T14:15:56.517 回答