Re: A more syntactically compact way?
- To: mathgroup at smc.vnet.net
- Subject: [mg63088] Re: A more syntactically compact way?
- From: albert <awnl at arcor.de>
- Date: Tue, 13 Dec 2005 03:42:03 -0500 (EST)
- References: <firstname.lastname@example.org>
- Sender: owner-wri-mathgroup at wolfram.com
Trevor Baca wrote: > I'm interested in creating two different "objects", which we'll call > obj1 and obj2. > > So I create two separate .m packages callled obj1.m and obj2.m. > > Then let's say that for each object I want to define a getLength > function (accessor) so that I can say both > >Â Â Â getLength[p] > > and > >Â Â Â getLength[q] > > where p is an obj1 and q is an obj2. > > The problem is that if both obj1.m and obj2.m declare a getLength > expression, then doing > > << obj1` > > works, but then adding > > << obj2` > > causes shadowing objections since, of course, the expression getLength > now lives in two contexts. > > So what's the right way to declare a simple expression (like getLength, > getName, getColor, etc) that operates on multiple different classes of > object defined in different packages? I would suggest to make a third package, e.g. called objCommon` which just contains all the function names and is "loaded" by both obj1.m and obj2.m with a Needs["objCommon`"]. You could think of this additional package as a definition of an interface which the various objects supply. Of course everything would be simpler and no extra package would be needed if you would be using strings instead of symbols. This also answers the question why one would like to use strings instead of symbols (I think that question has been raised in a previous answer to one of your questions). Despite the fact that there are limitations to this approach (as you have observerd) and of course it is unusual and uncomfortable to write something like "getName"[myobj] I don't think there is a problem to use just strings in that case. By the way, beside syntax there is no difference in making the same definitions DownValues instead of UpValues and e.g. make definitions for myobj["getName"] (or myobj@"getName" if you prefer), I guess many people would not have objections about using strings instead of symbols in this case which shows that it is mainly a matter of taste... > It would, of course, work to declare getLength, etc, in, say, the > System` or Global` context and NOT in any other context ... but that > just seems odd. Shouldn't expressions related to a package live in the > package? of course that is what everyone would expect from your package. If you are the only one to use it, it is a matter of taste and interoperability with other packages... hth, albert