OOP in Mathematica - A concrete example
- To: mathgroup at smc.vnet.net
- Subject: [mg37542] OOP in Mathematica - A concrete example
- From: atelesforos at hotmail.com (Orestis Vantzos)
- Date: Mon, 4 Nov 2002 02:44:12 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
There has been much discussion in this forum about the possibility of implementing OOP in Mathematica. It is simply not true that OOP is somehow incompatible with Mathematica's current structure. Nor is it true that the "pre-requisites are missing", like Andrew posted. Actualy it is unnervingly simple to implement OOP in a straightforward manner that respects all the fundamental concepts of Mathematica programming. Allow me to elaborate: The following code snippet implement a basic yet fully functional Level 1 (Delegate/Prototype System) OOP system within Mathematica: Unprotect[Dot];SetAttributes[Dot,HoldRest];Protect[Dot]; Object/: Object.method_Symbol[args___]:=Block[{$self=Object},Object[method[args]]]; Object@new[instance_Symbol]:=With[{ancestor=$self}, instance/:instance.method_Symbol[args___]:=Block[{$self=instance},instance[method[args]]]; instance[msg___]:=ancestor[msg]; instance@super[]=ancestor; instance]; This is the code needed to describe the Object class, and quite frankly one doesn't need much more! Let's see how it works: (* create an instance of Object called obj1 *) Object.new[obj1] (* now define a field for it called myField....notice the empty brackets; this is essentialy a function with no arguments*) obj1@myField[] = "OOP!" (* create a method in Object that accesses the field; notice the use of $self to refer to the object that actualy calls myMethod[] *) Object@myMethod[] := Print[$self.myField[]] (* let's call it from obj1 *) obj1.myMethod[] ---> "OOP!" In a Delegation OOP system like this, any object can also serve as a class. We can call obj1.new[obj2] to create a new object that inherits myField[] from obj1 and myMethod[] from Object. For more information on what a Level 1 OOP system is, please consult the OOP FAQ at http://www.cyberdyne-object-sys.com/oofaq2/ This is, as I said, a Proof-of-Concept implementation and can be greatly improved. It is very useful for the kind of discussion we are having here though, as one can program Mathematica in an Object-Oriented manner with it. Notice that it is already far more powerful than Maeder's package, as one can define methods with conditions, predicates, patterns, etc. ! I will be happy to discuss issues like Inheritance, Encapsulation, Dynamic Binding, etc. in future posts. Orestis Vantzos