2017-10-06 1 views
2

En Python, si j'ai une liste, je peux trouver l'index. Cela me permet de continuer à courir les identifiants que j'ajoute des choses.Comment faire une recherche bidirectionnelle dans Chapel pour des données de type dictionnaire?

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

donnent donc un légume (ou tubercules) Je peux trouver une carte d'identité pour elle. Étant donné une pièce d'identité, je peux trouver un légume (ou tubercule) correspondant.

Quel est le modèle équivalent dans Chapel pour un nombre inconnu d'objets et de pouvoir faire référence à partir du nom ou de l'identifiant?

+0

Si 'choses' sera grand, vous devriez vraiment utiliser un dictionnaire pour effectuer le mappage inverse. – kindall

Répondre

2

Vous pouvez utiliser push_back et find avec des tableaux rectangulaires 1D:

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 

Notez que find fait une recherche linéaire, de manière @kindall mentionné un dictionnaire est probablement le meilleur choix. Dans la chapelle, cela signifie un domaine/tableau associatif:

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); 

Deux tableaux associatifs seraient mieux si les indices ne sont pas dans une gamme dense.