Back: Programming
Previous: Module, Block, With
Next: Anonymous Functions

Programming in Mathematica

Packages

A Package is a Mathematica program which makes use of the Context-manipulation functions to hide local definitions and revise $ContextPath

Context Path

Initially, there are only the Global & System contexts.

$Context
$ContextPath

	Global`

	{Global`, System`}


Standard Packages (about 140 specialized programs included with the Mathematica distribution) add a new context to the front of the context path.


Get["Calculus`VectorAnalysis`"];
$ContextPath

	{Calculus`VectorAnalysis`, fDf`, Global`, System`}


A package uses these 4 context manipulation functions:


	BeginPackage[ "newcontext`" ];
		(*  list all new (nonprivate) functions *)
	Begin[ "`Private`" ];
		(* **** all the new definitions **** *)
	End[];
		(* use Protect[] and SetAttributes[] *)
	EndPackage[];


Sample Package fDf` (kept in a separate file, fDf.m)

BeginPackage[ "fDf`" ];

fdfPlot::usage = "fdfPlot[f,a,b] makes a plot of pure function
        f over the range [a,b], and superimposes the
        derivative of f as a dotted line.";
        
Begin["`Private`"];


label[f_] := FontForm[
			 StringJoin[
			  	"f[x]= ",
				ToString[f[x]],
				"     and f'[x] (dashed line)"],
			 {"Helvetica-Bold",24}];
				

fdfPlot[f_, tmin_, tmax_] := Module[

        	{df, g1, g2},  (* local variables *)
        
        df = D[f[t], t];
        
        g1 = Plot[f[t],{t,tmin,tmax},
        		PlotStyle->{Thickness[0.005],Hue[0.8]},
        		DisplayFunction->Identity];
        		
        g2 = Plot[df,  {t,tmin,tmax},
        		PlotStyle->{Dashing[{0.01,0.01}],Hue[0.55]},
        		DisplayFunction->Identity];
        		
        Show[g1, g2, PlotLabel->label[f],
        		DisplayFunction->$DisplayFunction];
        ]

End[];
			Protect[fdfPlot];
EndPackage[];


Using the package fDf


Get["fDf`"];		(*  read the package *)

Context  /@  {fdfPlot, label, g1}

	{fDf`, fDf`Private`, fDf`Private`}


fdfPlot[ ArcTan[#]-0.5&,  -5,  5]