TransWikia.com

Convenient value assignments in OOP

Mathematica Asked by Wjx on June 26, 2021

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.

One Answer

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

Answered by rnotlnglgq on June 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP