# Simple Problem with "AssociateTo"

Posted 9 years ago
7037 Views
|
2 Replies
|
0 Total Likes
|
 OK ... I am just catching up with the new features in Mathematica, Version 10. In particular, the addition of Associate and operations that go with this concept looks very interesting.I decided to write a simple repetitive operation using the command "AssociateTo". The purpose of my function called "extend" is to add an extra rule to the association, every time that Nest goes through its iterations. However, Mathematica does not seem to like the fact that I am performing a functional operation on an Association, rather than a variable with a value. Can anyone tell me how to make this work?'extend" takes an Association, and adds an extra rule to it. to do this, I just generate a random number and put it in the form x -> number However, the code below generates a bunch of errors. Clear[extend]; extend [b_] := Module[ {}, AssociateTo[b, x -> RandomInteger[{1, 10}] ] ]; a1 = <||>; Nest[extend, a1, 3] 
2 Replies
Sort By:
Posted 9 years ago
 thanks Peter - letry this out!
Posted 9 years ago
 Two problems:First: AssociateTo needs the name of a variable (a1), not the variable contents (<||>). Similar issues can appear with AppendTo, see the first Possible Issues example on its documentation page. AssociateTo has HoldFirst, so it itself is not evaluating a1, but it appears such an evaluation is happening along the way while passing the argument into your extend function. One way of addressing that problem, where each line needs to get evaluated separately, i.e. in its own cell: Clear[extend]; a1 = <||>; extend[] := Module[{}, AssociateTo[a1, x -> RandomInteger[{1, 10}]]]; Do[extend[], {3}]  Second: You are associating the same key 'x' with a different value in each iteration, so all previous values get overwritten each time.You will either have to create different keys in each step, or try to Merge them (the latter, of course, could more easily be achieved by first creating the list of values, and creating an Association from it with the single key only in the last moment).Hope this helps,Peter