A while ago I learned a trick which allows one to imitate object-oriented programming in MMA using SubValues
:
makeObj[identification_Integer] = Obj[identification];
makeObj[5]
(* Obj[5] *)
These can have "instance fields":
Obj[_]["field"] = 0 (* Default*);
And member functions:
Obj[id_Integer]["increase"] := (Obj[id]["field"]++;)
Obj[5]["increase"];
Obj[5]["field"]
(* 1 *)
However, in order to make an object, I have to identify it in makeObj
, otherwise my "field"
values will go to the default every time. Is there any implementation which allows me to create objects without explicitly naming the pointers to them?
In other words, can I make the compiler internally assign pointers? In Java, something like:
java.util.ArrayList<myObj> a = new java.util.ArrayList<MyObj>();
for(int i = 0; i < 10; i++)
a.add(new myObj());
a.get(5).doStuff();
can be easily done, but how would I do it in Mathematica? (without JLink
, of course)
If this is not possible, is there some way to have garbage-handling? Like:
Obj["delete", id_] :=
DeleteCases[SubValues[Obj], HoldPattern[Obj[id][_]] :> _]
(Except this doesn't work)
Obj
to some list, for instance, with a compiler-assignedid
. $\endgroup$Unique[]
anything useful? $\endgroup$Unique[]
is something that definitely works. The only issue is that when I did useUnique[]
in my actual problem, so many new symbols were created and defined that I can't help but imagine there's a solution which has garbage-handling. $\endgroup$