Re: same options for 30 functions?
- To: mathgroup at yoda.physics.unc.edu
- Subject: Re: same options for 30 functions?
- From: PERKINS TYLER R <perkins at spot.colorado.edu>
- Date: Sun, 27 Mar 1994 00:15:47 -0700 (MST)
Martin McClain (wmm at chem.wayne.edu) wrote:
>Is there any graceful way to provide a default option for 30 or more
>functions in a package? I want to let the user change defaults in the
>middle of a run, via SetOptions or some similar operator.
>[...]
>I would like to write
>
>f[a_, b_, g_String:(delayed assignment of $GroupName)]:= whatever
You almost have it! The trick is to make sure that $Groupname remains a
Symbol when the lhs of your definition is evaluated:
In[1]:= Clear[$GroupName]
In[2]:= f1[a_, b_, g_:$GroupName] := DoSomethingWith[g]
In[3]:= $GroupName = "name #1";
In[4]:= f1[1, 2, "name in arg. list"]
Out[4]= DoSomethingWith[name in arg. list]
In[5]:= f1[1, 2]
Out[5]= DoSomethingWith[name #1]
In[6]:= $GroupName = "name #2";
In[7]:= f1[3, 4]
Out[7]= DoSomethingWith[name #2]
By the way, why doesn't the following also work? Why should changing
the pattern g_ to g_String prevent the third argument below from being
recognized as optional?
In[8]:= Clear[$GroupName]
In[9]:= f2[a_, b_, g_String:$GroupName] := DoSomethingWith[g]
In[10]:= $GroupName = "name #2";
In[11]:= f2[1, 2]
Out[11]= f2[1, 2] (* Hmm! *)
Evidently, the answer is that the pattern g_String is checked against the
default value -- which is a Symbol, not a String -- when f2 is defined.
There is no match, so there is no default assigned to the third argument.
If $GroupName is already assigned, you could use a new variable to save its
value and then use the above method. Or you could do the following:
In[12]:= f3[a_, b_, g_:Hold[$GroupName]] := DoSomethingWith[ReleaseHold[g]]
In[13]:= f3[1, 2]
Out[13]= DoSomethingWith[name #2]
In[14]:= f3[1, 2, "name in arg. list"]
Out[14]= DoSomethingWith[name in arg. list]
In[15]:= $GroupName = "name #3";
In[16]:= f3[1, 2]
Out[16]= DoSomethingWith[name #3]
All this could have been accomplished more neatly by means of Default[] and
the _. pattern object:
In[17]:= functionSymbols = {f4, f30}; (* your 30 functions or whatever *)
In[18]:= Clear[$GroupName]
In[19]:= (Default[#] = $GroupName)& /@ functionSymbols;(* Assign defaults *)
In[20]:= f4[a_, b_, g_.] := DoSomethingWith[g] (* Define the *)
In[21]:= f30[x_, y_.] := DoSomethingElseWith[y] (* 30 functions *)
In[22]:= $GroupName = "name #4"; (* Default value *)
In[23]:= {f4[1, 2], f30[11]}
Out[23]= {DoSomethingWith[name #4], DoSomethingElseWith[name #4]}
In[24]:= {f4[1, 3, "nothing"], f30[11, "nuts"]}
Out[24]= {DoSomethingWith[nothing], DoSomethingElseWith[nuts]}
In[25]:= $GroupName = "name #5";
In[26]:= {f4[1, 2], f30[11]}
Out[26]= {DoSomethingWith[name #5], DoSomethingElseWith[name #5]}
Of course, we could also use Hold[] and ReleaseHold[] as above in case
$GroupName is already assigned.
Hope this helps.
Tyler Perkins perkins at colorado.edu