lom*_*per 4 agent-based-modeling netlogo
非常基本的问题,我不明白为什么我的 foreach 代码不执行任何操作(没有错误消息,但没有任何效果)。所以我的海龟有一个 3 维变量(意图),预设为[0 0 0]。我的最后一个问题比这复杂得多,但简单来说,我现在试图将该向量的每个维度更改为一,即[1 1 1]。
我创建了一个名为的过程change-intention,用于foreach产生此结果,但没有效果:
to change-intention
ask turtles [
(foreach intention [ x -> set x 1])
]
end
Run Code Online (Sandbox Code Playgroud)
我已经在观察者和海龟命令行以及单个海龟上尝试过此操作,但没有结果也没有错误。
谢谢!
几个问题。首先,列表是不可变的 - 如果您想更改列表中的值,则必须使用该值创建一个新列表。第二个是你不能使用set来做到这一点,你必须使用replace-item.
该代码是自包含的 - 打开一个新模型并尝试一下,将 testme 过程中的调用更改为不同的实现。过程change-intention1是您当前思考它的方式(无论如何是我的解释)。过程change-interpretation2是实现您的方法的方式,替换每个项目并创建新列表(解决已识别的问题)。
然而,更好的方法是使用过程,map而不是foreach因为所有值都立即更改,而不是循环遍历列表并处理每个值。当然,在您的真实模型中实现起来可能并不那么容易。
turtles-own [intention]
to testme
clear-all
create-turtles 1
[ set intention [0 0 0]
]
ask turtles [ type "before call:" print intention ]
change-intention2
ask turtles [ type "after call:" print intention ]
reset-ticks
end
to change-intention1
ask turtles
[ foreach intention
[ x ->
print "here"
set intention 1
]
]
end
to change-intention2
ask turtles
[ foreach intention
[ x ->
let pp position x intention
type "here:" print pp
set intention replace-item pp intention 1
]
]
end
to change-intention3
ask turtles
[ set intention map [ x -> 1 ] intention
]
end
Run Code Online (Sandbox Code Playgroud)