问题是原来设置follower的语句是
ask candidate [set follower myself]
而myself 不是代理集,是代理。这意味着,除非该语句更改,否则follower 永远不会是可数的:您可以计算代理集中有多少代理(也可以是 1 或 0 的代理集),但不能计算代理。
然后解决方案必须更改该语句,将 follower 初始化为不同的对象 - 一个适应多重性的对象(这意味着您可以在其上执行加法和可以测量的对象)。
- 代理集解决方案
正如我所说,代理集是可以计算的。实际上,代理集是count 操作的自然对象类型。因此,我们可以将follower 初始化为一个代理集。
一种方法是使用turtle-set:
...
ask candidate [set follower (turtle-set follower myself)]
...
在这种情况下,为了保持一致性,我还会更改 create-turtles population 位:
...
set follower (turtle-set)
...
这样,follower 从一开始就是所有海龟的代理集(从空代理集开始,而不是nobody)。
为了一致性,我更喜欢它,但请注意,这意味着所有询问是否follower = nobody 的条件都不再有意义:空代理集与nobody 不同!
实际上,如果你只是进行上述更改,然后点击setup,然后在命令中心运行count turtles with [follower = nobody],你会得到0。
改为运行 count turtles with [count follower = 0] 你会得到所有的海龟。
因此nobody 的条件必须相应更改;特别是,作为您问题对象的那个将变得整洁
...
let candidate one-of (turtles-at xd yd) with [count follower < 2]
...
所以,为了恢复整洁,让我将这三个更改按代码中的逻辑顺序排列:
; The initial declaration when you create turtles:
...
set follower (turtle-set)
...
; The condition where you test how many followers a turtle has:
...
let candidate one-of (turtles-at xd yd) with [count follower < 2]
...
; The action of adding a follower:
...
ask candidate [set follower (turtle-set follower myself)]
...
; Plus changing other instances where the original code says 'with [follower = nobody]'.
注意
正如你从turtle-set 的描述中看到的,它是一个非常灵活的原语:基本上它将任何东西都变成了一个(乌龟)代理集。
然而,在旅途中创建代理集的最常见方法是使用with。逻辑是代理集的子组仍然是代理集;鉴于with 只能在代理集上使用,它给你的只能是代理集。
然而,在我们的例子中,使用with 不会那么整洁/简单。
follower 变量可以很容易地使用 with 初始化为代理集:
ask candidate [set follower turtles with [who = [who] of myself]]
但是,这个唯一的命令每次都会将follower 设置为包含具有该特定who 的唯一海龟的代理集,因此无助于增加代理集的数量。
这时候事情会开始变得比仅仅使用turtle-set 更加复杂。
- 列表解决方案
另一种可以计数的对象是列表。可以想象,count 不计算列表,但 length 可以计算。
在这种情况下,我们只需将follower 初始化为一个列表,使用lput 或fput 将代理作为项目添加到列表中(取决于如何使用列表),计算列表的长度检查条件时。
更改反映了我们在 agentset 解决方案中所做的更改:
; The initial declaration when you create turtles:
...
set follower (list) ; or
set follower []
...
; The condition where you test how many followers a turtle has:
...
let candidate one-of (turtles-at xd yd) with [length follower < 2]
...
; The action of adding a follower:
...
ask candidate [set follower (lput myself follower)]
...
; Plus changing other instances where the original code says 'with [follower = nobody]'.
如果您想跟踪海龟跟随领导者的顺序,使用列表将很有用。事实上,虽然列表是有序对象,但代理集是无序的(实际上,每次调用该代理集时,代理集中的代理都会以随机顺序出现/执行)。