MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Lightweight Structs - Practical Example (Data Types in Mathematica)

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


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

Here's how I implement the above (after reviewing a number of posted

A named struct employs Mathematica's subscripted variables feature,
composed as so:
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;

I've found the following pointers from others useful/interesting:  - Maeder's ADT
material - OOP Package
by Orestis Vantzos, which implements Classes.

  • Prev by Date: Re: Re: Questions regarding MatrixExp, and its usage
  • Next by Date: Re: Extracting information from lists
  • Previous by thread: Re: preparing multiple choice questions
  • Next by thread: Re: Lightweight Structs - Practical Example (Data Types in Mathematica)