4
$\begingroup$

How do I get Association to act like List in the following?

list = {a};
assoc = <|x -> a|>;
a = 1;
{list, assoc}
{{1}, <|x -> a|>}

The List picks up the newly assigned value of a, but the Association does not. And why does Association behave like this?

$\endgroup$
  • 2
    $\begingroup$ You are mistaken. List does not pick up the new value. Just observe ??list and you see that it still contains the initial a. The moment you evaluate list, it is replaced by its content, which is {a} and then Mathematica tries to further evaluate this by applying rules that are associated with a. Therefore, your question cannot simply be answered since your understanding of the behavior is not correct. What now? $\endgroup$ – halirutan Jan 3 '15 at 6:54
6
$\begingroup$

As halirutan notes the original value of list is retained; only its evaluation is changed by the new assignment a = 1.

Likewise the evaluation of the Association is also changed:

assoc = <|x -> a|>;
a = 1;
assoc[x]
1

In Mathematica 10.0.2 assoc is also printed with the evaluated form of a:

assoc
<|x -> 1|>

Its definition remains unchanged however:

?assoc
Global`assoc

assoc=<|x->a|>

To actually update the definition of list one could use list = list because the RHS fully evaluates. However this is not the case with the Association. You can force an evaluation of the values with a Map operation:

assoc = Identity /@ assoc;

?assoc
Global`assoc

assoc=<|x->1|>

The behaviors illustrated may change as Association is further developed. See for example:

$\endgroup$
  • $\begingroup$ I'm running Mathematica 10.0.2.0, and when I execute assoc, I get <|x -> a|>, not <|x -> 1|>. $\endgroup$ – CarbonFlambe Jan 4 '15 at 12:31
  • $\begingroup$ @Fructose I am a Windows 7 user. What about you? $\endgroup$ – Mr.Wizard Jan 4 '15 at 12:57
  • $\begingroup$ OS X Yosemite 10.10.1. $\endgroup$ – CarbonFlambe Jan 4 '15 at 23:33
  • $\begingroup$ One can also use Evaluate /@ assoc. $\endgroup$ – CarbonFlambe Feb 14 at 16:33

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.