5
$\begingroup$

I am attempting to create a Package and so am saving a notebook with the code from Mathematica's example

BeginPackage["Collatz`"]

Collatz::usage = "Collatz[n] gives a list of the iterates in the 3n+1 \
problem,
         starting from n. The conjecture is that this sequence always
         terminates."

Begin["`Private`"]

Collatz[1] := {1}

Collatz[n_Integer] := Prepend[Collatz[3 n + 1], n] /; OddQ[n] && n > 0

Collatz[n_Integer] := Prepend[Collatz[n/2], n] /; EvenQ[n] && n > 0

End[]

EndPackage[]

And save it as a .m file. However, when I try to Get the file it doesn't work. So I did FilePrint as in their example and everything is commented.

Get["Desktop\Collatz.m"]

(* ::Package:: *)

(* ::Input:: *)
(*BeginPackage["Collatz`"]*)
(**)
(*Collatz::usage="Collatz[n] gives a list of the iterates in the 3n+1 problem,*)
(*        starting from n. The conjecture is that this sequence always*)
(*        terminates."*)
(**)
(*Begin["`Private`"]*)
(**)
(*Collatz[1]:={1}*)
(**)
(*Collatz[n_Integer]:=Prepend[Collatz[3 n+1],n]/;OddQ[n]&&n>0*)
(**)
(*Collatz[n_Integer]:=Prepend[Collatz[n/2],n]/;EvenQ[n]&&n>0*)
(**)
(*End[]*)
(**)
(*EndPackage[]*)

Am I doing something incorrect?

$\endgroup$
1
  • $\begingroup$ The solution is to convert the relevant cells into initialization cells... $\endgroup$ – chris Aug 3 '15 at 19:10
8
$\begingroup$

Only initialization cells will be saved as uncommented code.

Check Cell -> Cell Properties -> Initialization Cell and Initialization Group.

You can also use Code cells (instead of Input), which have the Initialization Cell property by default. Alt-8 or Command-8 inserts a code cell.

You can check that it is an initialization cell by looking at the top right corner of the cell which has an extra cross:

Mathematica graphics

Anything which is not an initialization cell will be commented out.

$\endgroup$
1
$\begingroup$

The accepted answer explains well why this happens and what you can do to fix it. One thing you can do when writing a package is first create a blank text file with the .m or .wl file extension, and then open it up in Mathematica.

The file is interpreted as a package, not a notebook, and so

  • Any new cell created is an initialization cell, no need to create a special cell or modify cell properties.
  • When saved, all cells are written to the file as plain text
  • Output cells are not written to the file.
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.