MathGroup Archive 2002

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

Search the Archive

Re: Newbie-type question: structured data types in Mathematica?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg37589] Re: [mg37521] Newbie-type question: structured data types in Mathematica?
  • From: Alexander Sauer-Budge <ambudge at MIT.EDU>
  • Date: Tue, 5 Nov 2002 05:08:52 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

Hi Ken, I'm new to Mathematica too. The easiest thing to do is to use a 
rule list:

rect1={width->2,height->1};
area1[rect_]:=width height/.rect;
area1[rect1]

but this is slow and cumbersome. Another approach which works well if 
you are imperatively minded is to use down-values to build a database:

rect2[width] = 2;
rect2[height] = 1;
?rect2
area2[rect_]:=rect[width] rect[height];
area2[rect2]

but this makes it hard to pass the data around anonymously. To remedy 
this, you can use a symbolic head to manage a packed-list:

rect[height_,width_][height]:=height;
rect[height_,width_][width]:=width;

area3[rect_]:=rect[width] rect[height];
area3[rect[3,4]]

but then you cannot assign to it in an imperative style. If you aren't 
working imperatively, however, you can formalize this last approach:

MakeStructure[struct_,membrs_]:=Module[{names=Part[#,1]&/@membrs},
     (* define down values for member access *)
     SetDelayed[Apply[struct,membrs][#],#]&/@names;
     (* define type test *)
     SetDelayed[Symbol[ToString[struct]<>"Q"][expr_],
       MatchQ[expr,Apply[struct,membrs]]];
     (* define member offsets *)
     Set[struct[#],First[First[Position[names,#]]]]&/@names;]
MakeStructure[Rect,{height_,width_}]
?Rect
ReplacePart[Rect[4,4],6,Rect[width]]
Area[r_?RectQ]:=r[width] r[height];
Area[Rect[3,7]]

Or you can modify it slightly to be in the spirit of Complex:

MakeStructure[struct_,membrs_]:=Module[{names=Part[#,1]&/@membrs},
     TagSetDelayed[struct,#[Apply[struct,membrs]],#]&/@names;
     SetDelayed[Symbol[ToString[struct]<>"Q"][expr_],
       MatchQ[expr,Apply[struct,membrs]]];
     ]
MakeStructure[Rect,{Height_,Width_}]
?Rect
Area[r_?RectQ]:=Height[r] Width[r];
Area[Rect[3,7]]

Still, this method isn't quite rich enough as is for large data 
structures because you need to know the ordering to create them.

I'm sure other more knowledgeable and insightful list members will have 
other and better ideas on managing simple structured data without too 
much hOOPla.

Alex


On Sat, 2 Nov 2002 Kenneth McDonald wrote:
> I've been looking for a while, and I can't find a way to create any
> sort of structured data type in Mathematica, i.e. one with named fields
> that contain other values. Does such a beast exist?



  • Prev by Date: RE: making a block diagonal matrix
  • Next by Date: RE: Re: RE: DrawGraphics Figure-8 && CPU Strangeness
  • Previous by thread: Re: Newbie-type question: structured data types in Mathematica?
  • Next by thread: ADMIN: Newsgroup message problem fixed