WolframLang: Writing a Package

By Xah Lee. Date: .

here's how to write a package.

What is WolframLang / Mathematica Package?

A package is like other programing language's library.

Effectively, it is a file of function definitions. and a way to specify which name are exported (when user loads the package), and which name are private to the package.

Package Structure

A package has this structure of Context for controlling which symbol is to be exported. [see WolframLang: Context (Namespace)]

BeginPackage[ "PackageContextName`" ]; (* symbols to be exported here. *) Begin["Private`"]; (* code here. *) End[]; EndPackage[];

By convention, the symbols you want to export start with captical letters.

(* example of a package.
this package exports 2 symbols, named: Add1, Add2.
it has a private symbol named: xone
*)

(* declare a namespace *)
BeginPackage[ "AddStuff`" ];

(* 
Usage docstring here.
But most importantly, they declare the exported symbols.
If you don't want to write docstring, you should at least put exported symbols here.
*)

Add1::usage= "Add1[n] adds 1 to n.";

Add2::usage= "Add2[n] adds 2 to n.";

(* start a new private namespace *)
Begin["Private`"];

(* example of a private symbol, variable *)
xone = 1;

Add1[n_] := n + xone;

Add2[n_] := n + 2;

End[];

EndPackage[];

Note: WolframLang package file names should end in .wl. Before 2010, they end in .m.

WolframLang: Package, Load File