Lightweight Structs - Practical Example (Data Types in Mathematica)

*To*: mathgroup at smc.vnet.net*Subject*: [mg63373] Lightweight Structs - Practical Example (Data Types in Mathematica)*From*: "Frank Iannarilli" <frankeye at cox.net>*Date*: Tue, 27 Dec 2005 04:42:43 -0500 (EST)*Sender*: owner-wri-mathgroup at wolfram.com

Hi, I've followed the various recent and older threads on implementing: - abstract data types (ADTs) - typedefs, structs, record-types (a la C language) - object-oriented programming (OOP) constructs, such as classes I find *multiple* instantiations of a particular named structure-type to be useful in calculations-oriented notebooks. For instance, in defining a structure called "Sensor", containing various state/parameter fields, I can carry about the structure instances "mine", "yours", etc, without needing to explicitly marshall together all the instance-associated variables for each calculation (function invocation). Here's how I implement the above (after reviewing a number of posted suggestions): A named struct employs Mathematica's subscripted variables feature, composed as so: Sensor[ID][fieldname] where we use an arbitrary variable name ("Sensor") for the structure (typedef) name, unique "ID" subscript (for each of multiple instantiations), and "fieldname" sub-subscripts. Sensor[mine][radius] = 6; Sensor[yours][radius] = 7; Then the named struct instance is passed around as Sensor[ID], whose Head is Sensor. p = Sensor[mine]; q = Sensor[yours]; The struct's "member data" (fields) can be accessed by name: In> p@radius Out> 6 In> q@radius Out> 7 Furthermore, since the Head of the struct instance is "Sensor", separately defined Sensor "member functions" can take a struct-typed pattern argument: myFunction[s_Sensor] := Module[{}, Print[s@radius]] In> myFunction[p] Out> 6 Can define a "constructor", which returns Sensor[id] "handle": makeSensor[id_] := Module[{}, Sensor[id]@radius = 0; Sensor[id]] I've found the following pointers from others useful/interesting: http://library.wolfram.com/infocenter/Conferences/4680/ - Maeder's ADT material http://library.wolfram.co.jp/infocenter/Conferences/5773/ - OOP Package by Orestis Vantzos, which implements Classes.