pari-gp

Looping through keys in Map() object


I'm working with Map() and need an efficient method to loop through all the keys. Specifically the keys are non matrices, and the image is a t_List of real vectors. My current method is to turn the Map into a matrix and loop through like below

M = Map();
...\\fill up the map with stuff
matM = Mat(M);
for(i=1, matsize(M)[1], 
L = matM[i,2];
\\ proceed to do stuff with L
);

However my understanding is that matM will create a copy of the data inside M, which I'd like to avoid if possible. My only other thought is to create a supplementary list of the ideals as the Map is filled, and then to iterate through that. Is there a better way to handle this?


Solution

  • You can loop the map using a foreach().

    {
        foreach(M, item,
    
            my(key = item[1][1]);
            my(value = item[1][2]);
    
            print(Str(key, ": ", value));
        );
    }
    

    It looks a little bit weird because the variable item contains a vector whose first position it's another vector with the key and the value.

    If you're going to use it often you could define a function like this:

    foreachMap(M, expr) = foreach(M, item, expr(item[1][1], item[1][2]));
    
    
    lambda = (key, value) -> print(Str(key, ": ", value));
    foreachMap(M, lambda);