0

问题来了,

假设我们有一个数据类型和一组数据类型:

data Color=red(int n, str name)|black(int n, str name);

set[Color] coloredBalls={red(1,"a"), red(2,"b")};

我想遍历集合的元素并更改元素如下:

for(Color aColor <- coloredBalls)
{
    if(aColor.n == 2)
        aColor.str="bb"

    //I would like to change the node: red(2,"b") to red(2,"bb") in the set coloredBalls
    //but am unable to express it in Rascal, unless I recourse to using a "Map", which I
    //think obfuscates the code quite a bit. Maybe using switch/visit with case does the trick?
}
4

1 回答 1

2

有很多方法可以构建您想要的新集合(当然,您实际上无法更改现有集合)。

您可以使用访问:

coloredBalls = visit (coloredBalls) {
  case red(a,b) => red(a, b + "b")
}

或者使用一个理解is

coloredBalls = { x is red ? x[name=name+"b"] : x | x <- coloredBalls};

或者在生成器端使用模式匹配:

coloredBalls = {red(a, b + "b") | red(a,b) <- coloredBalls} + { y | y <- coloredBalls, !(y is red)};

或者在理解的插入端使用模式匹配:

coloredBalls = {red(a,b) := c ? red(a,b+"b") : c | c <- coloredBalls};
于 2014-12-01T16:32:10.193 回答