4
$\begingroup$

Currently, from a variety of examples, and (mostly) the template generated by my IDE, I get:

(* Mathematica Package *)

(* :Title: MyPkg *)
(* :Context: MyPkg` *)
(* :Author: Me *)
(* :Date: 2015-12-17 *)

(* :Package Version: 0.3 *)
(* :Mathematica Version: 10.3 *)
(* :Copyright: (c) 2015 Me *)
(* :Keywords: *)
(* :Discussion: *)


(* USAGE:

    SetDirectory[NotebookDirectory[]];
    Get["MyPKg`"];

*)

BeginPackage["MyPkg`"]

Unprotect@@Names["MyPkg*"];
ClearAll@@Names["MyPkg*"];

MyPkg::usage = "Test package";

f::usage = "Solve it";
g::usage = "Show the puzzle";


(* ::Package:: *)

Begin["`Private`"]


(* ******************** Public exported functions and definitions *)

f[x_] := p[x]/2;
g[x_] := f[x] + q[x];

(* ******************** Internal supporting functions and definitions *)

p[x_] = x + 5;
q[x_] = x + 10;

End[] (* `Private` *)


EndPackage[]

But I'm confused about whether this is the right structure, or whether it does what I expect it to. Specifically:

  1. Is it really necessary or correct to define the package name in so many places? In the example, I have it in Title, Context, and BeginPackage, which seems redundant and prone to error.
  2. How do I ensure that reimports of my package (with Get reliable clear the symbols defined there before defining them again. I'v seem several different approaches, but while, Unprotect@@Names["MyPkg*"]; and ClearAll@@Names["MyPkg*"]; seem the most common, the don't seem to do anything. (And note again: I've had to specify the package name explicitly; is there a way to avoid that?)
  3. What is (* ::Package:: *) for? Where should it go? I can't find that documented anywhere.
  4. And what good is does the distinction among public, private, and exported symbols do anyway? If I ?"GCHQ`*" I see all of them, even those that are private or local!
  5. Some examples show ("protected") definitions between End[] (* Private *) and EndPackage[]; what goes there?

Any other tips on the correct structure for a package would also be appreciated. I can't seem to find consistent documentation on this, and much of what I can find is surpassingly old.

$\endgroup$
13
  • $\begingroup$ Reading this book: Programming in Mathematica 3rd Edition written by Roman Maeder, who is the key developer of Mathematica of version 1. $\endgroup$ – xyz Dec 19 '15 at 14:59
  • 3
    $\begingroup$ You've seen Creating Mathematica packages ? $\endgroup$ – Yves Klett Dec 19 '15 at 15:22
  • $\begingroup$ @YvesKlett: Yes, and? $\endgroup$ – orome Dec 19 '15 at 15:28
  • $\begingroup$ You are aware that comments are marked with (* *)? That should answer questions 1 and 3. $\endgroup$ – Sjoerd C. de Vries Dec 19 '15 at 15:30
  • 1
    $\begingroup$ Yes, that's what I'm saying. $\endgroup$ – Sjoerd C. de Vries Dec 19 '15 at 15:37