Message Boards Message Boards

2
|
6397 Views
|
2 Replies
|
6 Total Likes
View groups...
Share
Share this post:

Association and Mathematica OOP combination

Posted 7 years ago

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 Replies

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

POSTED BY: Eric Smith
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract