Message Boards Message Boards

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

Can an Association contain a function that evaluates its own contents

I have tried several variations without success.

Association[{a -> 1, b -> 4, c -> 5, p :> Plus[#a + #b] &}],

<|a -> 1, b -> 4, c -> 5, p -> Plus[#a, #b] &|>,

<|a -> 1, b -> 4, c -> 5, p -> Plus["a", "b"]|>,

<|a -> 1, b -> 4, c -> 5, p :> Plus["a", "b"]|>,

...

POSTED BY: Roger M Kolaks
4 Replies

I just came across the resource function AssociationTemplate that allows values to refer to other values. Neat!

POSTED BY: Rohit Namjoshi
Posted 1 year ago

If the association will be static, i.e. a and b won't change, then you could set p at "construction" time:

NewThing[a_, b_] := <|"a" -> a, "b" -> b, "p" -> a + b|>

Sounds like you've already found a solution, but in case you want to consider another solution, you might try a wrapper.

AugmentedAssociation[data_Association]["p"] := data["a"] + data["b"];
AugmentedAssociation[data_Association][k_] := data[k]

Which can be used like this:

MyThing = AugmentedAssociation[<|"a" -> 2, "b" -> 3|>];
{MyThing["a"], MyThing["b"], MyThing["p"]}
(* {2, 3, 5} *)

Or a different type of wrapper where you can provide the functions in the data:

SpecialAssociation[data_Association][k_] := If[Function === Head[data[k]], data[k][data], data[k]];
MyThing = SpecialAssociation[<|"a" -> 2, "b" -> 3, "p" -> (#a + #b &)|>];
{MyThing["a"], MyThing["b"], MyThing["p"]}
(* {2, 3, 5} *)

What would make this reallly slick is if you defined these wrappers to work with the other Association-related functions (e.g. Lookup), which you could do with TagSetDelayed.

POSTED BY: Eric Rimbey

Thanks. I decided I could get by sending the data to another data structure.

I'm not sure I understand what you mean by a constructor pattern. Unless you mean a data input form.

POSTED BY: Roger M Kolaks
Posted 1 year ago

Can you add a use case? Not sure this can be done anonymously at all, but given a sample pattern of usage, there might be a way to do it for that specific usage pattern. For example, if the association is static, you could use a constructor pattern. Or you might be able to create a new data structure that mimics an association. Or you could operate on your association with functions rather than accessors. Etc. Just depends on how you want to use it.

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