如何在 Chapel 中进行双向查找以获取类似字典的数据?
How do I do a bi-directional look up in Chapel for dictionary-like data?
在Python中,如果我有一个列表我可以找到索引。这允许我在添加内容时保留 运行 个 ID。
> things = []
> things.append("spinach")
> things.append("carrots")
> things.index("carrots")
1
所以给一种蔬菜(或块茎)我可以找到它的 ID。给定 ID,我可以找到匹配的蔬菜(或块茎)。
在 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 中,这意味着关联 domain/array:
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);
如果索引不在密集范围内,两个关联数组会更好。
在Python中,如果我有一个列表我可以找到索引。这允许我在添加内容时保留 运行 个 ID。
> things = []
> things.append("spinach")
> things.append("carrots")
> things.index("carrots")
1
所以给一种蔬菜(或块茎)我可以找到它的 ID。给定 ID,我可以找到匹配的蔬菜(或块茎)。
在 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 中,这意味着关联 domain/array:
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);
如果索引不在密集范围内,两个关联数组会更好。