Re: how to create a mathematica package
- To: mathgroup at smc.vnet.net
- Subject: [mg111134] Re: how to create a mathematica package
- From: "Nasser M. Abbasi" <nma at 12000.org>
- Date: Wed, 21 Jul 2010 07:14:22 -0400 (EDT)
- References: <i199df$q4p$1@smc.vnet.net> <i20q7s$kid$1@smc.vnet.net> <i23k2u$erk$1@smc.vnet.net>
- Reply-to: nma at 12000.org
On 7/20/2010 12:43 AM, Istv=E1n Zachar wrote:
> I think you should also protect the public variables of the package at
> the end to prevent the user to overwrite them.
>
> Istvan
When you said the above, I made some experiments, and I think what I
need to do in addition to what you said is to also Clear the function nam=
e.
So, now I have it like this:
BeginPackage["foo`"]
f::usage = "f[x]"
Begin["`Private`"]
Unprotect[f];
Clear[f];
f[x_] := Module[{}, x^2];
Protect[f];
End[]
EndPackage[]
The Unprotect[f] is needed for the case when the package is reloaded
again, else one will get an error trying to define something already
protected (from the first loading)
The Clear[f] is needed, because suppose I had written
f=4
Then wanted to load the package
Get["foo.m"]
Then I would get an error trying to define a function 4[x_]. This is
Unprotect[f] does not also Clear[f]. So needed to explicitly do a Clear[f=
].
The last Protect is needed to prevent me from overwriting the name of
the function 'f' after I have loaded the package as in:
Get["foo.m"]
f=4;
Does the above seem like the canonical package layout for a simple
package?
I've also corrected couple of typos (thanks Bill Rowe) and updated the no=
te:
http://12000.org/my_notes/how_to_write_package_in_mathematica/index.htm
If I can improve this more, pls let me know.
--Nasser