views:

201

answers:

2

Can someone offer some advice on how to get started with mathematica packages?

I can save the following in a file named "Foo.m". When I run the input cell in that file, I can see the effects reflected in $ContextPath variable.

BeginPackage["Foo`"]

bar::usage = "barfunction";

Begin["`private`"]
bar[w_] := w;
End[];

EndPackage[];

However, in my notebook I have the following:

#include<foo>
SetDirectory[ToFileName[{$HomeDirectory, "My Documents", "mathematica"}]];
Needs["Foo`"]
$ContextPath

But the needs call is failing for some reason, and the $ContextPath remains unchanged.

Edit

I believe that I've got a partial solution working now, the cell in my file wasn't marked as an initialization cell - and whilst I can now <<Foo', Needs["Foo"]` still isn't working correctly.

+2  A: 

Check to make sure the saved file, "Foo.m", is on your $Path, which tells Mathematica which directories to look in when trying to load packages, much like the PATH environment variable in Unix or Windows.

EDIT: $ContextPath won't be changed unless there's an actual BeginPackage statement (or you manipulate it directly using Set or Block or something).

EDIT the second: One thing to check is what

FileNames["Foo.m", $Path]

returns. What you're describing does sound a little strange, though.

Pillsy
Pilly, is it sufficient to simply assume that if the file is in the current working directory (which I believe is set by SetDirectory), and "." is in $Path, that the file should be found?
Andrew Walker
+1  A: 

Either form should work. When a file is loaded using Get (or <<) or Needs, the directory on the top of the DirectoryStack[] is searched first, and then the $Path is searched. (SetDirectory does not change $Path, so FileNames["Foo.m", $Path]won't find Foo.m.) However, FindFile by default searches Directory[] and $Path. You can test it by doing the following:

FindFile["Foo`"]
SetDirectory[<Foo dir>]
FindFile["Foo`"]

it should return

$Failed
<Foo dir>
<Foo dir>/foo.m

If FindFile can find Foo.m then Needs should be able to find it. In general, I put my packages in $UserBaseDirectory/Applications, and Needs picks them up just fine.

rcollyer