1

I am working with this data structure which I call an "associationList", which has the following format:

<| key1->{value1, value2,...}, key2->{value1,value2,...},...|>

I want to have the function Add[assocList_,key_,value_] add key->{value} to the associationList by reference. I have the following code:

Add[assoc_, key_, elt_] :=
  If[Head@assoc[key] === Missing,
   AppendTo[assoc, key -> {elt}],
   AppendTo[assoc[key], elt]];
SetAttributes[AddToAssocList, HoldFirst];

The Add function works for this example:

y=<||>;
Add[y,1,a];
(* y is <|1->{a}|> *)
Add[y,1,b];
(* y is <|1->{a,b}|> *)

But when I change the example to the following, I get an error:

y={<||>};
Add[y[[1]],1,a];
(* y is <|1->{a}|> *)
Add[y[[1]],1,b];
(* Error - Association - "<|1->{a}|> in the part assignment is not a symbol" *)

Using any type of Hold doesn't seem to help. Any ideas?

Lucas Mumbo
  • 162
  • 8

1 Answers1

1

The answer is to change assoc[key] in Add to assoc[[ Key[key] ]]. This works because assoc[key] gives an association, while assoc[[ Key[key] ]] gives a reference to the association.

Lucas Mumbo
  • 162
  • 8