RE: data structure / object
- To: mathgroup at smc.vnet.net
- Subject: [mg16377] RE: [mg16293] data structure / object
- From: "Ersek, Ted R" <ErsekTR at navair.navy.mil>
- Date: Thu, 11 Mar 1999 02:16:48 -0500
- Sender: owner-wri-mathgroup at wolfram.com
antoine.zahnd at iprolink.ch wrote: ------------------------------- I would to do the following with Mathematica 3.0 : Define a data structure, fot example point[x,y], and then overload operators, and in particular the output operator. That is to say to be able to write p=point[1,2];q=point[-1,3];r=p+q pt[0,5] Thank you very much for your solutions, (and pointers to books/references). antoine.zahnd at iprolink.ch ------------------------------------ If you use the typical style for Mathhematica programming (lhs:=rhs) the definition would be associated with Plus, and would slow down evaluation of Plus (a frequently used feature). Instead I give point an UpValue (using lhs^:=rhs) in the line below. By giving point an UpValue I associate the definition with point. Since I use patterns like (x1_?NumericQ) the rule below is only used when both arguments of point are numeric. If you get rid of each use of (?NumericQ), you will have no restrictions on the arguments. In[1]:= ClearAll[point]; point[x1_?NumericQ,y1_?NumericQ]+ point[x2_?NumericQ,y2_?NumericQ]^:= point[x1+x2,y1+y2] In[2]:= point[1,2]+point[-1,3]+point[a,b] Out[2]= point[0,5]+point[a,b] In the line above the rule wasn't used for the term point[a,b]. -------------------------- If you don't care if the arguments of point are numeric the following rule will work. Besides that it may be faster when you are adding a lot of points. Notice: (terms_) would stand for one term. (terms__) stands for two or more terms. You must use Unevaluated so this definition doesn't run in circles forever. In[3]:= ClearAll[point]; Plus[terms__point]^:= Thread[Unevaluated[Plus[terms]],point] In[4]:= point[1,2]+point[-1,3]+point[a,b] Out[4]= point[a,5+b] In the line below we see the definition above even works when point has more than two arguments. This could be useful. In[5]:= point[2,5,3]+point[3,-2,4] Out[5]= point[5,3,7] ------------------- Regards, Ted Ersek