Message Boards Message Boards

0
|
5361 Views
|
6 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Pure functioned Closure, a variant of the Mathematica OOP

Posted 7 years ago

In the previous post, "Closure" as a variant of the Mathematica OOP was presented. Next, i introduce a closure which method is written by the pure function. This sample shows also a initialization method for the OOP instance.

First code is a class definition,

class[nam_[init_]] := Module[{local = init},
  nam & ^:= ++local;
  ]

Second code is a construction of instances with local value initialization as,

class[counter1[0]]; class[counter2[100]];

Then we can call the initialized instance as a pure function,

{counter1 &, counter2 &, counter1 &, counter2 &}

We can get the results as,

{1, 101, 2, 102}

Let's examine the "counter1"

?counter1

We'll get as,

Global `counter1

counter1&^:=++local$231

Counter1 was encapsulated by OOP, and is still a global symbol, we can do as,

{counter1 = 0, counter1 &, counter1, counter1 &}

The result is,

{0, 3, 0, 4}

6 Replies

HI, Podkalicki,

Its a good question on the characteristics of the OOP. Please try "? counter1, or ? counter2". You will find the backyard of OOP and the meaning of UpSet. Unfortunately, the Mathematica help document for the UpSet is too insufficient to understand the incredibly strong power of that function.

I understand what UpSet is doing. I just don't see any advantage of it with respect to my example with SetDelayed. The more than later you need to call Function[counter] to run a function while it is not consistent with how pure functions work, you'd expect something like Function[counter][] at least. So I don't see the point of & here.

Just to emphasize, I'm not very experienced with OOP and those notes are only from MMA point of view. If you could elaborate why UpSet is better here and why Function[counter] -> value makes sense? I would appreciate that.

Best

POSTED BY: Kuba Podkalicki

This sample was intended to show the functions of UpSet which is the key of OOP style. So, the closure "counter" is intending to show the OOP style extendable-ness not to show the other advantages. So, this sample use the pure-function as un-named-ness then we can call the encapsulated function with the "&"ed object name only.

Regards,

Hi, not "nam[] := ++local;", but ”nam & ^:= ++local;" .

I saw what you wrote. My question is: why not nam[]:=..? Calling the method with counter1[] is more natural than Function[counter1] or equivalently counter1 &.

POSTED BY: Kuba Podkalicki

Sorry if I missed the point, but why? Isn't Function[counter1] returning a value unexpected? What is wrong with class[nam_[init_]] := Module[{local = init}, nam[] := ++local;] and counter1[] later?

POSTED BY: Kuba Podkalicki
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