在 Python 中,如果我有一个列表,我可以找到索引。这使我可以在添加内容时继续运行 ID。
> things = []
> things.append("spinach")
> things.append("carrots")
> things.index("carrots")
1
所以给一种蔬菜(或 block 茎)我可以找到它的 ID。给定一个 ID,我可以找到匹配的蔬菜(或 block 茎)。
在 Chapel 中,对于未知数量的对象并能够从名称或 ID 进行引用的等效模式是什么?
请您参考如下方法:
您可以对一维矩形数组使用 push_back 和 find:
var A : [1..0] string;
A.push_back("spinach");
A.push_back("carrots");
const (found, idx) = A.find("carrots");
if found then writeln("Found at: ", idx);
// Found at: 2
请注意,find 进行线性搜索,因此正如@kindall 提到的那样,字典可能是更好的选择。在 Chapel 中,这意味着关联域/数组:
var thingsDom : domain(string);
var things : [thingsDom] int;
var idxToThing : [1..0] string;
// ...
// add a thing
idxToThing.push_back(something);
const newIdx = idxToThing.domain.last;
thingsDom.add(something);
things[something] = newIdx;
assert(idxToThing[things[something]] == something);
如果索引不在密集范围内,则两个关联数组会更好。
