0

I do need to setup an association in Mathematica, in which the value of a key is a function of the value of another key (of the same association-object). Currently I am putting a dummy value at when the Association is created and then, with a further operation, change the dummy variable to the correct value.

I would really do that directly during the declaration. Any trick for that?

SS = Association[n -> 1.0, x -> 2, dummy -> 0]
SS["dummy"] = 100*SS[[Key[n]]] + SS[[Key[x]]]
LaoZe
  • 33
  • 4
  • I am not sure what you want to achieve here, you know the associated values to `n` and `x` so what you are doing doesn't make much sense here. Perhaps this is some example of what you are really trying to achieve but I would say you've probably taken the wrong path already. If you would tell us what you are really trying to do, maybe we could help with that. – Qubit Dec 09 '19 at 12:28
  • I need the dummy key in the first line of code to be a combination of other the key n and the key x (e.g. dummy=f(n,x)). And I want to do that without using the second line of code. – LaoZe Dec 09 '19 at 12:46

1 Answers1

0
f[n_, x_] := Association["n" -> n, "x" -> x, "dummy" -> 100*n + x]
SS = f[1., 2]

Edit: If you insist on a "one-liner":

SS=Function[{n,x}, Association["n" -> n, "x" -> x, "dummy" -> 100*n + x]][1.,2]

or even

SS=Association["n" -> #1, "x" -> #2, "dummy" -> 100*#1 + #2] &[1., 2]
Alan
  • 9,410
  • 15
  • 20
  • Please add explanation as well along with the code, to make it understandable how it will solve the problem. – Arun Vinoth-Precog Tech - MVP Dec 09 '19 at 22:56
  • That's not an one-liner and it does the same as: SS["dummy"] = 100*SS[[Key[n]]] + SS[[Key[x]]] And moreover it forces me to create a new function f when I want to change the relation in "dummy". Unfortunately that is worse than manual inserting the formula after the association assigned. – LaoZe Dec 10 '19 at 15:29
  • 1
    @LaoZe It's the right way. You will always have to write new code when you "change the relation in `dummy`". One liners are overrated, but you can have a one liner; see the edit. – Alan Dec 10 '19 at 17:41
  • @Alan of course I would need to change of relation if it is different, I just do not want to do it via another function everytime. The oneliner solution you provided seems pretty smart indeed. – LaoZe Dec 11 '19 at 10:06