Re: Returning rules from functions inside a package context
- To: mathgroup at smc.vnet.net
- Subject: [mg82439] Re: Returning rules from functions inside a package context
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Sat, 20 Oct 2007 05:53:19 -0400 (EDT)
- Organization: The Open University, Milton Keynes, UK
- References: <ff9rjl$4mv$1@smc.vnet.net>
Art wrote: > The following question has been asked and answered in a variety of > ways in this forum, but I am new to Mathematica and am still not sure what is > best practice after doing Trace of various trivial statements for the > past few hours. > > For example, I would like f[] below to return {a->1.}, not > {A`Private`a->1.}. > > BeginPackage["A`"] > f::usage = "" > Begin["`Private`"] > > f[] := FindFit[{{0, 0}, {1, 1}}, a x, {a}, x] > > End[] > > EndPackage[] > > The use of Rule[] in different scoping constructs is confusing. I do not know whether the following technique could qualify as the best practice, still, I would suggest to define the variable "a" as "Global`a", so we force its definition to reside in the *Global* context (symbols located in the *Global* context are referred by Mathematica just by their names). For instance, we could write the package TestRule.m as BeginPackage["TestRule`"] f::usage = "How to return a nice rule from a package." Begin["`Private`"] f[] := FindFit[{{0, 0}, {1, 1}}, Global`a x, {Global`a}, x] End[] EndPackage[] Then we can check that the rule returned by the function f[] is of the desired form. In[1]:= << TestRule` In[2]:= f[] Out[2]= {a -> 1.} Regards, -- Jean-Marc