MathGroup Archive 2009

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

Search the Archive

Default Symbol Names in Package Functions

  • To: mathgroup at smc.vnet.net
  • Subject: [mg96109] Default Symbol Names in Package Functions
  • From: "David Park" <djmpark at comcast.net>
  • Date: Thu, 5 Feb 2009 04:39:44 -0500 (EST)

Suppose that I have a routine that generates or tests an expression in terms
of a variable. For example, I might have something like:

 

foo1[var_]:=var^2+var+1

 

Then a user can generate the polynomial expression in any variable that she
specifies. But then I realize that most the time the user will use 'x' as
the variable symbol.  So I use a default argument as follows:

 

foo1[var_: x] := var^2 + var + 1

 

However, when I put this in a package it doesn't work because the private
package context gets used on the default symbol.

 

BeginPackage["TestPackage`"];

foo::usage="foo[var] uses an argument with a default value.";

Begin["`Private`"];

foo[var_:x]:=var^2+var+1;

End[];

EndPackage[];

 

foo[]

1 + TestPackage`Private`x + TestPackage`Private`x^2

 

So, I think I know how to fix that. I just specify a Global context for the
default value.

 

BeginPackage["TestPackage`"];

foo::usage="foo[var] uses an argument with a default value.";

Begin["`Private`"];

foo[var_:Global`x]:=var^2+var+1;

End[];

EndPackage[];

 

foo[]

1 + x + x^2

 

But this mechanism gives me two problems:

 

1) When the package is loaded it creates the symbol Global`x. If there is
another package that creates the symbol SecondPackage`x,  say, then there is
a conflict and among other things the symbol gets colored in red. (I
actually have a case of this with another person's very good package.)

 

2) If I have a somewhat more general function foo[expression_,
var_:Global`x] where some tests are done on expression in terms of the
variable x, then when I try to document this in a Version 6 function page,
it doesn't work. That is because any expression in x in the documentation
page will have a special CellContext that does not match Global`x.

 

So I conclude that one should just not use default arguments that pass
symbol names in package functions. There are too many potential problems.
Make the user always enter the symbol. Still, I wonder if anyone has some
better idea for doing this?

 

David Park

djmpark at comcast.net

 <http://home.comcast.net/~djmpark> http://home.comcast.net/~djmpark/  



  • Prev by Date: Re: Printing (v7)
  • Next by Date: Re: Loop programming; how do i do this ???
  • Previous by thread: Changing the height of baseline in Histograms
  • Next by thread: Re: Default Symbol Names in Package Functions