0
$\begingroup$

for those who have seen it, I have deleted my previous question, as suggested by @Αλέξανδρος Ζεγγ,

The goal :

Modifying dynamically the list on which a mapping is done

I try to give you a concrete example:

When I do this :

 S = Association[];
AssociateTo[S, {1 -> "one", 2 -> "two", 3 -> "three"}]

While[Length[S] > 0,
 (KeyDropFrom[S, Keys[S][[#]]];
    Print[S];) & /@ Range[Length[Keys[S]]]]

The output is :

    Out[19]= <|1 -> "one", 2 -> "two", 3 -> "three"|>

During evaluation of In[18]:= <|2->two,3->three|>

During evaluation of In[18]:= <|2->two|>

During evaluation of In[18]:= Part::partw: Part 3 of {2} does not exist.

During evaluation of In[18]:= <|2->two|>

During evaluation of In[18]:= <||>

As you can see, mathematica does not understand that I want the list on which the mapping is done to be modfied dynamically, S is only evaluated once at the beginning of the mapping : the desired output would be just <||>, with no errors. I just want to modify dynamically the liston which the mapping is done, my goal is not to delete all the keys of an association...

Can anyone help me ?

thank you in advance.

$\endgroup$
  • $\begingroup$ S is modified dynamically, that is why Print[S] changes on every evaluation.The problem is that Range[Length[Keys[S]]] is only evaluated once. $\endgroup$ – Rohit Namjoshi May 25 at 17:25
  • 2
    $\begingroup$ why not While[Length[S] > 0, (KeyDropFrom[S, #]; Print[S];) & /@ Keys[S]] or While[(Length[KeyDropFrom[S, #] > 0]; Print[S];) & /@ Keys[S]]? $\endgroup$ – kglr May 25 at 17:38
  • $\begingroup$ @RohitNamjoshi, yes indeed, does not solve my problem, but I will edit my post. $\endgroup$ – yfs May 25 at 20:00
  • $\begingroup$ @kglr, does not solve my problem Keys[s] is still evaluated once. Again my goal is not to empty S... $\endgroup$ – yfs May 25 at 20:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.