Re: Advice on defining a data structure in Mathematica

*To*: mathgroup at smc.vnet.net*Subject*: [mg44114] Re: [mg44014] Advice on defining a data structure in Mathematica*From*: Omega Consulting <info at omegaconsultinggroup.com>*Date*: Thu, 23 Oct 2003 07:15:08 -0400 (EDT)*Sender*: owner-wri-mathgroup at wolfram.com

At 04:14 AM 10/17/2003, Mark Coleman wrote: >Greetings, > >I'm an econometrician that has used Mathematica for several years. Now I've >finally decided to sit down and generalize some of my code to better >handle time series data. I'd like to get some opinions on good ways to >define a time series "data structure". Ideally this structure would >carry all of the important information about the series, e.g, the >numercial values, the corresponding dates, the frequency, information >for how to convert the series from one frequency to another (say >monthly to quarterly), the textual name of the time series (say GDP), >and some brief descriptive information. > >Obviously this could be structured as a list of lists, but that strikes >me as not very elegant. I've seen examples of Mathematica code that creates >objects that remind me of traditional record data structures using up >values. Is this the preferred approach? > >Thanks, > >-mark The typical way is to give the type a special head and put the data inside. (It doesn't matter how the data is organized as long as it makes sense to you.) MyType[ ... data ... ] This way when you write a function you can test for the type by matching the head. function[type_MyType] := ... Or overload a built-in function with an upvalue MyType/: a_MyType + b_MyType := ... And whenever you work with the type don't do things like data = MyType[...]; value = data[[4]]; Because this depends on how the data is stored in the type (which you may decide to change). Instead, create and use constructors and selectors. data = constructor[...]; value = selector[data]; Then if you decide to change how the data is stored, you only need to change the constructors and selectors. And everything else will continue to work. It's also useful to hide the internal data in output. You can do this with Format or MakeBoxes. Format[type_MyType] := "-MyType-" or MakeBoxes[type_MyType, form_] := "-MyType-" -------------------------------------------------------------- Omega Consulting "The final answer to your Mathematica needs" http://omegaconsultinggroup.com