Skip to main content
8 of 9
added 36 characters in body
Szabolcs
  • 238.9k
  • 32
  • 653
  • 1.3k

Quick start tutorial

This is a quick start guide on how to set up a package following the typical structure. It does not explain why it is usually done that way, and it does not discuss other possible way to do it. That is left to the other answers here (especially Leonid's), as well as the official documentation.

Follow this guide to quickly set up your first package, so you have something concrete to experiment with. After that you must read the other answers and the references below, to gain a more complete understanding.

What is a package?

It is a text file with the .m extension that contains function definitions, and adheres to certain conventions. It can be loaded with Needs or Get to make the functions available for use.

How to create a basic package?

A basic package consists of a single file. More complex, multi-file packages won't be discussed here.

  1. Choose a name for your package. For this example I will assume the name MyPack.

  2. Type the source code into a file named MyPack.m.

  3. The file must adhere to the following structure:

    BeginPackage["MyPack`"]; (* Export section *) (* Every function that the package provides will have a usage message here. *) (* There will be no function definitions in this section, only usage messages. *) (* Public functions will have names starting with capitals, by convention. *) MyFunction::usage = "MyFunction[x]"; Begin["`Private`"]; (* note ` character both before and after Private *) (* Implementation section *) (* Function definitions will go into this section *) MyFunction[x_] := helper[x] (* All functions which are not public, and are only used in the internal implementation of the package, go into this section. These have non-capital names by convention. *) helper[z_] := z^2 End[]; (* `Private` *) EndPackage[]; (* MyPack` *) 
  4. The file must be placed into a directory which is in $Path.

    Packages are typically installed into FileNameJoin[{$UserBaseDirectory, "Applications"}]

How to load and use a package?

Evaluate

<< MyPack` 

If MyPack.m is in $Path, it will be loaded.

Now the function MyFunction is available for use.

References


Notes

The description in this guide is oversimplified on purpose, to make it easy to follow. When I stated things in absolute terms, I "lied" a little bit here and there: you don't need to strictly follow this exact structure. However, this structure does represent the best practices, and going beyond it does require an understanding of contexts. The other answers here should be considered required reading after you have set up your first package.

Szabolcs
  • 238.9k
  • 32
  • 653
  • 1.3k