这是问题,
假设我们有一个数据类型和一组数据类型:
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?
}
答案 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};