更改集合中元素的属性并将其放回集合中

时间:2014-12-01 15:25:01

标签: rascal

这是问题,

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

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?
}

1 个答案:

答案 0 :(得分: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};