0

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?

  • I've ended up doing the second method and store a supplementary t_List of the keys. At least this will not copy the image elements, and t_List can be updated in place. Would still be happy to have a more definitive answer if this is really the best way! – Punchinello Aug 04 '22 at 16:54

1 Answers1

2

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);
Elián Fabián
  • 100
  • 1
  • 6
  • 1
    Woah, this is an excellent solution, thank you! I didn't know lambdas existed in Pari either – Punchinello Sep 17 '22 at 13:11
  • The two assignments in the original solution could be simplified to my([key, value] = item[1]); – K.B. Feb 22 '23 at 09:32
  • Of course there is no need to introduce 'lambda' in the namespace, you can use an anonymous closure as in foreachMap(M, (k,v) -> print(Str(k, ": ", v))) – K.B. Feb 22 '23 at 09:34