代码之家  ›  专栏  ›  技术社区  ›  Simon

在不保存附属定义的情况下,如何保存与Mathematica中符号关联的[]定义?

  •  4
  • Simon  · 技术社区  · 14 年前

    内置的mathematica命令 Save[file, symbol] 使用 FullDefinition[] 查找定义 symbol 以及所有附属定义。

    例如,命令

    a:=b
    c:=2a+b
    Save[ToFileName[NotebookDirectory[],"test.dat"],c]
    

    生成包含

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

    我有一个程序,里面有很多美化的东西 MakeBoxes 我做的类型定义 希望在保存多个单独结果时保存。

    对于上面的简单示例,我不希望 a := b 定义已保存到文件中。有人知道一个让这一切发生的好方法吗?

    3 回复  |  直到 14 年前
        1
  •  9
  •   Janus    14 年前

    根据文件, Save 使用 FullDefinition 而你想用的是它 Definition . 使用A Block 我们可以覆盖任何符号的全局定义,特别是替换 全定义 具有 定义 跑步时 保存 :

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

    魔法效果:

    c := 2*a + b
    

    编辑。用正确的属性进行包装:

    SetAttributes[truncatedSave, HoldRest]
    truncatedSave[filename_, args__] := Block[{FullDefinition},
       FullDefinition = Definition;
       Save[filename, args]];
    
        2
  •  1
  •   Dr. belisarius    14 年前

    我想

    DumpSave["test1", c]  
    

    那样做。

    样例代码:

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

    _____________________
    Global`a
    _____________________
    Global`c
    c:=2 a+b
    
        3
  •  1
  •   Dr. belisarius    14 年前

    警告-警告-我不知道我在做什么

    刚刚发现这个浏览帮助系统随机。

    从未使用过 贯通 …不管怎样,似乎都能满足你的需要。

    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  
    

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

    编辑…在列表上工作,稍微按住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