Netlogo中有array[index1,index2]数据结构吗?
Is there an array[index1,index2] data structure in Netlogo?
是否有 Netlogo 的扩展允许创建使用 "array[i,j]" 样式符号访问的多维数组?我发现使用 item 会导致代码冗长且难以阅读,而且我对 2D 列表上的任何内容都感到迷惑(尽管我意识到其他人对此非常满意)。
谢谢!
据我所知,自己做一个原语很容易。这里有几个不同的实现可以给你一些想法:
使用递归:
to-report nested-get [ lst indices ]
ifelse empty? indices [
report lst
] [
report nested-get (item first indices) (but-first indices)
]
end
使用reduce:
to-report nested-get [ lst indices ]
report reduce [ [ l i ] -> item i l ] fput lst indices
end
我选择将索引放在参数列表之后,以便更好地匹配您希望的语法,但您可以考虑将它们放在前面,以与 item
相对应。记者调用如下:
observer> show nested-get [ [ "a" "b" "c" ] [ "d" "e" "f" ] ] [1 2]
observer: "f"
不幸的是,如果您想使用变量或报告器作为索引,则需要使用 list
而不是 []
:
observer> let i 0 let j 1 show nested-get [ [ "a" "b" "c" ] [ "d" "e" "f" ] ] (list i j)
observer: "b"
语法支持任意数量的嵌套。您还可以制作维度特定版本,以简化常见情况的语法:
to-report item2 [ i j lst ]
report item j item i lst
end
现在有一个名为 array 的 netlogo 扩展
这是一个代码示例:
extensions [array ]
to setup
set ex array:from-list n-values 10 [0]
set i 1
while [i < 10 ][
array:set ex i i + 1
]
end
是否有 Netlogo 的扩展允许创建使用 "array[i,j]" 样式符号访问的多维数组?我发现使用 item 会导致代码冗长且难以阅读,而且我对 2D 列表上的任何内容都感到迷惑(尽管我意识到其他人对此非常满意)。
谢谢!
据我所知,自己做一个原语很容易。这里有几个不同的实现可以给你一些想法:
使用递归:
to-report nested-get [ lst indices ]
ifelse empty? indices [
report lst
] [
report nested-get (item first indices) (but-first indices)
]
end
使用reduce:
to-report nested-get [ lst indices ]
report reduce [ [ l i ] -> item i l ] fput lst indices
end
我选择将索引放在参数列表之后,以便更好地匹配您希望的语法,但您可以考虑将它们放在前面,以与 item
相对应。记者调用如下:
observer> show nested-get [ [ "a" "b" "c" ] [ "d" "e" "f" ] ] [1 2]
observer: "f"
不幸的是,如果您想使用变量或报告器作为索引,则需要使用 list
而不是 []
:
observer> let i 0 let j 1 show nested-get [ [ "a" "b" "c" ] [ "d" "e" "f" ] ] (list i j)
observer: "b"
语法支持任意数量的嵌套。您还可以制作维度特定版本,以简化常见情况的语法:
to-report item2 [ i j lst ]
report item j item i lst
end
现在有一个名为 array 的 netlogo 扩展
这是一个代码示例:
extensions [array ]
to setup
set ex array:from-list n-values 10 [0]
set i 1
while [i < 10 ][
array:set ex i i + 1
]
end