开发者

How do I Save[] definitions associated to a symbol in Mathematica without saving subsidiary definitions?

开发者 https://www.devze.com 2023-01-23 05:14 出处:网络
The built-in Mathematica command Save[file, symbol] uses FullDefinition[] to look up the definition symbol and all of the subsidiary definitions.

The built-in Mathematica command Save[file, symbol] uses FullDefinition[] to look up the definition symbol and all of the subsidiary definitions.

For example, the commands

a:=b
c:=2a+b
Save[ToFileName[NotebookDirectory[],"test.dat"]开发者_如何学Python,c]

produces the file test.dat containing

c := 2*a + b
a := b

I have a program with a lot of prettifying MakeBoxes type definitions that I do not want to be saved when I Save[] the many separate results.

In terms of the simple example above, I do not want the a := b definition saved to the file. Does anyone know a neat way to make this happen?


According to the documentation, Save uses FullDefinition while what you want is for it to use Definition. Using a Block we can override the global definition of any symbol, and in particular replace FullDefinition with Definition while running Save:

Block[{FullDefinition},
  FullDefinition = Definition;
  Save[filename, c]
  ];
FilePrint[filename]
DeleteFile[filename]

The magic works:

c := 2*a + b

EDIT. Wrapping things up with the right attributes:

SetAttributes[truncatedSave, HoldRest]
truncatedSave[filename_, args__] := Block[{FullDefinition},
   FullDefinition = Definition;
   Save[filename, args]];


I think

DumpSave["test1", c]  

Does that.

Sample code:

a := b;
c := 2 a + b;
DumpSave["test1", c];
Clear[a, c];
<< test1
?a
?c

Out

_____________________
Global`a
_____________________
Global`c
c:=2 a+b


Warning - Warning - I don't know what I am doing

Just found this browsing the help system randomly.

Never before used RunThrough ... anyway seems to do what you want.

Clear["Global`*"];  
a := b;  
c := 2 a + b;  
mathcommand =  StringReplace[First[$CommandLine], "MathKernel" -> "math"];
outputfile = "c:\\rtout";
RunThrough[mathcommand <> " -noprompt", Unevaluated[Put[Definition[c], "c:\\rtout"]]]
FilePrint[outputfile]
Clear[a, c];
<< "c:\\rtout"
DeleteFile[outputfile]
?c  

Out

c := 2*a + b
_______________________________
Global`c
c:=2 a+b

Edit.. Works on lists with a little Hold-Fu

Clear["Global`*"];

(*Trick here *)
f[l_] := Definition @@ HoldPattern /@ Unevaluated@l;
SetAttributes[f, HoldFirst];

a := b;
c := 2 a + b;
d := 3 a + b;
mathcommand = StringReplace[First[$CommandLine], "MathKernel" -> "math"];
outputfile = "c:\\rtout";

RunThrough[mathcommand <> " -noprompt",Unevaluated[Put[Evaluate[f@{c, d}], "c:\\rtout"]]]

(* test *)

FilePrint[outputfile]
Clear[a, c, d];
<< "c:\\rtout"
DeleteFile[outputfile]  
?c  
?d   

0

精彩评论

暂无评论...
验证码 换一张
取 消