Association and Mathematica OOP combination

With Association, Mathematica OOP can represent another style of programming. I’d like to introduce a sample of associated function selector. Let’s consider next sample.

new[nam_] := Module[{},
  Function[nam[x_]] ^:= <|square :> (x^2), cube :> (x^3)|>
  ]

Then, a construction of instance named “test” can be realized as,

new[test];

We can show the encapsulation effect of the Mathematica OOP, that is represented as variables in the CLASS are being global.

{cube = 0, test[2] = 0, test[3] = 0, square[x_] := x + 2, square[5]}

Whereas, we can get the results as,

{test[2] &[square], Function[test[2]][cube]}

and the result shows that the style of the function which can select the method with additional parameter as,

{4, 8}

where, calling the instance “test” with parameter “2” following “square” returns 4, and following “cube” returns 8.

2 Likes

Thanks for this post. What about properties? So if you wanted to calculate and save values/properties for use later, how could you do this? I’m thinking something like

new[nam_, d_: 2] := Module[{},
  Function[nam[x_]] ^:= <|square :> (x^2), cube :> (x^3)|>;
  Function[nam] ^= <|area :> nam[d] &[square], 
    volume :> nam[d] &[cube]|>]
new[test,3]
test&[area]

But that’s not quite right

1 Like

Hi, Smith,

When the property means the local value, you can set the local value with a class defined as,

new[nam_] := Module[{x},
  nam[y_] & ^:= x = y;
  nam & ^:= <|square :> (x^2), cube :> (x^3)|>
  ]

then, construct a instance and set a local value following the calculation as,

new[test];
test[2] &;
{test &[square], test &[cube]}

{4, 8}

other calculation can be done with another local value as,

test[3] &;
{test &[square], test &[cube]}

{9, 27}
3 Likes