5
$\begingroup$

I have some "complicated" data that I want to encapsulate into a "struct":

For instance (imagine that data have several fields):

data=<|"A"->6,"B"->2|>
var=myType[data]

The advantage is that it is easy to filter your arguments:

doSomething[myType[d_]]:=d

(* usage: *)
doSomething[var]

Now I want to allow this:

var["B"] <- must return 2

But I do not know how to do that, any idea?


What I have done so far:

myType /: Key[k_][myType[d_]:=d[k]

This works for syntax like:

Key["B"][var]

but not for

var["B"]
$\endgroup$
5
$\begingroup$
ClearAll[myType]
myType /: myType[data_Association][s_String] := data[[s]]

var = myType[<|"A" -> 6, "B" -> 2|>];
var["B"]

2

$\endgroup$
  • $\begingroup$ Thanks again Henrik, my questions are too easy :-) $\endgroup$ – Picaud Vincent Feb 1 at 12:09
  • $\begingroup$ You're welcome. $\endgroup$ – Henrik Schumacher Feb 1 at 12:12
  • 3
    $\begingroup$ This definitely works, though it's good to notice that this sets a SubValue for myType, not an UpValue. $\endgroup$ – Sjoerd Smit Feb 1 at 13:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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