1

It is possible to implement OOP in Mathematica using something like

obj=c[<|a->1,b->2|>]

and it's convenient to extract value from the object by setting:

c[a_][b_]:=a[b]
obj[a]

1

but how to write a convenient value assignment so that this form of set action is valid?

obj[a]=3

3

obj

c[<|a->3,b->2|>]

Thanks!


My (obviously unsuccessful) attempts:

c /: Set[o : (c[a_])[b_], val_] := (o=c[ReplacePart[a,Key[b]->val]])

This obviously won't work as the HoldFirst attribute of Set prevent the pattern matching of c[a_]

but without it:

Set[o_[b_], val_]/;Head[o]==c := (o=c[ReplacePart[a,Key[b]->val]])

Set is Protected and simply matching all o_[b_] type and then filter by Head is simply so inefficient.

Michael E2
  • 235,386
  • 17
  • 334
  • 747
Wjx
  • 9,558
  • 1
  • 34
  • 70

1 Answers1

0

Kernel definitions precede over user definitions, and subvalues precede over upvalues. As @HenrikSchumacher commented, Language`SetMutationHandler should be used.

rnotlnglgq
  • 3,740
  • 7
  • 28