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$

1 Answer 1

5
$\begingroup$
ClearAll[myType]
myType /: myType[data_Association][s_String] := data[[s]]

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

2

$\endgroup$
3
  • $\begingroup$ Thanks again Henrik, my questions are too easy :-) $\endgroup$ Feb 1, 2019 at 12:09
  • $\begingroup$ You're welcome. $\endgroup$ Feb 1, 2019 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$ Feb 1, 2019 at 13:35

Your Answer

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

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