1
$\begingroup$

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.

$\endgroup$
3
  • 4
    $\begingroup$ You have to use Language`SetMutationHandler. See here for detailed info an an example. $\endgroup$ Jun 15, 2018 at 6:46
  • $\begingroup$ @HenrikSchumacher Thanks! I will have a look! $\endgroup$
    – Wjx
    Jun 16, 2018 at 4:14
  • $\begingroup$ Please try to determine the place of your approach among the ones listed (and taxonomized) here: "Which Object-oriented paradigm approach to use in Mathematica?". Consider posting an answer (in the referred MSE discussion.) $\endgroup$ Dec 25, 2021 at 14:05

1 Answer 1

0
$\begingroup$

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.