Message Boards Message Boards

0
|
1470 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:

How do I change a value in an association?

It is not clear to me why this function does not work:

setHome[c_, i_] := (c[["h"]] = i);

testCd = <|"s" -> "a", "v" -> 1, "h" -> 0, "n" -> 0, "x" -> 0|>
setHome[testCd, 5]
testCd

But this works perfectly:

the2s = {<|"s" -> "a", "v" -> 2, "h" -> 0, "n" -> {"a", 3}, "x" -> 0|>,
  <|"s" -> "b", "v" -> 2, "h" -> 0, "n" -> {"b", 3}, "x" -> 0|>,
  <|"s" -> "c", "v" -> 2, "h" -> 0, "n" -> {"c", 3}, "x" -> 0|>,
  <|"s" -> "d", "v" -> 2, "h" -> 0, "n" -> {"d", 3}, "x" -> 0|>}

start2s = {28, 41, 2, 15};
(the2s[[#, "h"]] = start2s[[#]]) & /@ Range[Length[the2s]]
MatrixForm[the2s]

Can someone make clear to me what I am missing?

POSTED BY: Roger M Kolaks
2 Replies

Thank you.

I think I will investigate AssociateTo.

For some reason Mathematica's implementation of databases continues to confound me. Even after writing PickOS for a few years back in the long ago and Vax for many, not too much more recent, years and a handful of other database languages in the whenever.

For some reason it doesn't seem to sink it.

POSTED BY: Roger M Kolaks
Posted 1 year ago

The special syntax the uses Part and Set (e.g. c[["h"]] = i) doesn't work for constants. So, for example, this doesn't work:

<|"s" -> "a", "v" -> 1, "h" -> 0, "n" -> 0, "x" -> 0|>[["s"]] = 1

Given your definition for setHome:

setHome[c_, i_] := (c[["h"]] = i)

when you execute setHome[testCd, 5], this does NOT become testCd[["h"]]=1. The expression setHome[testCd, 5] immediately evaluates to setHome[<|"s" -> "a", "v" -> 1, "h" -> 0, "n" -> 0, "x" -> 0|>, 5], and thus we're applying Part/Set to a constant expression, not a symbol.

In your second example, Function has the HoldAll attribute, so nothing is getting executed in the body of the function until after the slot replacements have occurred. So in that case, we have Part/Set working on a symbol.

If you want, you can set the HoldAll attribute for setHome (SetAttributes[setHome, HoldAll]), and it should work (because testCd won't immediately be evaluated, but will be inserted into the function definition as just the symbol testCd).

Having said all of that, I would prefer using AssociateTo anyway.

POSTED BY: Eric Rimbey
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract