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)
Objto some list, for instance, with a compiler-assignedid. – VF1 Oct 20 '12 at 19:53Unique[]anything useful? – Mr.Wizard Oct 20 '12 at 19:56Unique[]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. – VF1 Oct 20 '12 at 19:58ReplaceAllis simply an alternative to usingSubValuesfor doing the same thing. The problem is that I still have to explicitly construct every parameter which the rules handle in the example. – VF1 Oct 20 '12 at 20:02Temporarysymbols is what I want, if that is possible. – VF1 Oct 20 '12 at 20:05Modulecreates symbols with attributeTemporary, and they can persist outside ofModule, so this may be what you need. – Mr.Wizard Oct 20 '12 at 20:06Module[{x = 1}, makeObj[x]; Obj[x]["increase"]; Obj[x]["field"]]still addsHoldPattern[Obj[1]["field"]] :> 1to theSubValuesofObj– VF1 Oct 20 '12 at 20:19