2

In Python, if I have a list I can find the index. This allows me to keep running IDs as I add things.

> things = []
> things.append("spinach")
> things.append("carrots")
> things.index("carrots")
1

So give a vegetable (or tuber) I can find an ID for it. Given an ID, I can find a vegetable (or tuber) to match.

What is the equivalent pattern in Chapel for an unknown number of objects and being able to reference from the name or the id?

Brian Dolan
  • 3,086
  • 2
  • 24
  • 35

1 Answers1

2

You can use push_back and find with 1D rectangular arrays:

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

Note that find does a linear search, so as @kindall mentioned a dictionary is probably the better choice. In Chapel, that means an associative 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);

Two associative arrays would be better if the indices are not in a dense range.

benharsh
  • 396
  • 1
  • 8