Re: Returning rules from functions inside a package context
- To: mathgroup at smc.vnet.net
- Subject: [mg82457] Re: Returning rules from functions inside a package context
- From: Szabolcs Horvát <szhorvat at gmail.com>
- Date: Sat, 20 Oct 2007 06:02:32 -0400 (EDT)
- 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.}.
Don't return 'a' at all! You cannot know whether users of your package
will have 'a' defined or not. So it is a very *bad* idea to create
Global` symbols in your package.
Use
f[] := a /. FindFit[{{0,0}, {1,1}}, a x, {a}, x]
instead. This way 'x' and 'a' will stay inside A`Private` and they
won't interfere with the user's own symbols.
Note that if you're defining such a function outside a package, in a
Global context, (and you cannot be sure that 'x' and 'a' won't be
defined later), then the definition should be
f[] := Module[{a,x}, a /. FindFit[{{0,0}, {1,1}}, a x, {a}, x]]
to isolate 'a' and 'x'. The environment inside a package can be
controlled, so Module[] is not strictly necessary there.
>
> 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.
>
> Thanks.
>
>
--
Szabolcs