NetLogo:参考 'foreach' 中的当前项目

NetLogo: Refer to current item in 'foreach'

假设我有

globals [x]
patches-own [number]

to set.x
  set x list 3 8
end

to set.number
  ask patches [
    set number random 10
  ]
end

现在假设我希望 number = 3 或 number = 8 的每个补丁将 number 更改为 0.

我想使用 foreach 来完成,但我不明白如何使用 foreach 遍历 x ,当发生这种情况时,请参考 x.

中使用的当前值

类似

to bring.to.zero
  foreach x ask patches with [number = *the current value from x*]
    [set number 0]
  ]
end

我很清楚这最后一段代码在语法上都是无效的,事实上我不知道如何表达星号之间的段落;我无法全神贯注于如何让它发挥作用。 可能是我对NetLogo的使用不够,但是NetLogo词典中foreach的描述对我也没有帮助。

请注意,我用不同的方法解决了特定问题:

to bring.to.zero
  ask patches [
    if member? number x [set number 0]
  ]
end

但我仍然很好奇 foreach

你很接近,问题是你需要使用匿名过程将当前迭代映射到命令;这将起作用 foreach x [a -> ask patches with [number = a][set number 0]],这里 aforeach 读取列表 x

的当前值

这是我制作的一个小脚本,在 setup 中,补丁将采用从 0 到 9 的随机颜色(因此 pcolor 就像您的变量编号的代理)和列表 x 将被填充,make-red x 中带有 pcolor 的补丁将变为红色,最后 blue-the-red 将通过转动 [= 使所有非红色补丁变为蓝色=22=] 到 list 并用 foreach.

迭代它
globals [x]

to setup
  clear-all
  ask patches [set pcolor random 10]
  set x list 3 8
end

to make-red
  foreach x [ a -> ask patches with [pcolor = a] [set pcolor red] ]
end

to blue-the-red
  ; ask every non-red patch to change its color to blue
  ; also helps to illustrate how an agent-set becomes a list
  foreach [self] of patches with [pcolor != red] [a -> ask a [set pcolor blue] ]
end