Hi Henrick,
I am going to take a stab at this, but your question is written in a very complicated way (try to ask a smaller simpler question, if at all possible; that way people may be able to help you quicker).
Let's start with an association (note that you can type four spaces at the beginning of a line to make it look like code):
x = <| "a" -> 1, "b" -> 2, "c" -> 3 |>
And a function which gets called with an association:
f[y_Association] := y
Now I can call f
with x
:
f[x]
And this returns the association:
<| "a" -> 1, "b" -> 2, "c" -> 3 |>
OK, so far, so good. Not let's say you want to return an association but with a modified key or value. First, let's do it the wrong way:
f[y_Association] := ( y["a"] = 5; y)
If you do this and call it with:
f[x]
you get an error:
(Association::setps) <|a->3,b->2,c->3|> in the part assignment is not a symbol.
The reason for that is that y
is not a variable but the expression that you passed in. So this:
f[x]
becomes:
f[<| "a" -> 1, "b" -> 2, "c" -> 3 |>]
and the code on the right hand side becomes:
( <| "a" -> 1, "b" -> 2, "c" -> 3 |>["a"] = 5; <| "a" -> 1, "b" -> 2, "c" -> 3 |>)
which leads to the error because you can not assign to an association.
To fix this you need to use a Module
with a temporary variable to which you assign your association:
f[y_Association] := Module[ {z=y}, z["a"]=5; z ]
Now if you call it with x
:
f[x]
you get no error and a plausible useful result:
<|"a" -> 5, "b" -> 2, "c" -> 3|>
If you want to add a key, you can do something like this:
f[y_Association] := Module[{z = y}, z["d"] = 5; z]
If you want to drop a key you can use either:
f[y_Association] := KeyDrop[y, "a"]
or:
f[y_Association] := Module[{z = y}, KeyDrop[z, "a"]]
(Module
is not needed here, since you're not trying to assign to an expression in this case).
Finally, if you want your original x
to be modified by f
you simply assign to it:
x = f[x]
So here, f
is called with x
, uses a temporary variable to modify the expression, returns the result, and assigns that result to x
.
I think the last bit might solve the second part of your question.
Hope this helps.