I have long functions that I use often in code. So instead to put them every time in a cell and execute it, I would like to save them on the hard drive and then reuse it inside other code in order to shorten it. I tried Put, Get, DumpSave and so on but either I do not use these correctly or they are not intended for this.
What I would like to to is the following:
Define the function f[x_]:=…
Save it giving it a name
Get it back in code:
code1
code2
f[x]
code3
…
I have the impression that this is something very easy to do but I am unable to get the info out of the Mathematica documentation. So can anyone help me? Thanks in advance.
Edit: to be more clear, here is what I made:
Put[x^2, "test.m"];
f = Get["test.m"]
g[x_] := f
g[2]
The wished output is 4 of course but what I get is x^2. I tried out a handful of other combinations but never obtained what I am looking for…
every time you call the function g, it just load the file and return x^2. Your second method works because Evaluate around the second argument overwrites the HoldAll attribute of SetDelayed.
Ok thanks for your info. Let’s go a step further now. How would you store and get back this function:
f[z_] := Block[{n}, n = 1; Do[n = n + 1, {z}]; Return[n]];
If I use Put, it will be evaluated and I get the error Do::iterb: Iterator {z} does not have appropriate bounds. When I use Unevaluated before Block, I can Put it but then I get the same message with
From what I understand, in your first example, you are saving an expression, your second example, you are saving a procedure.
I recommend using Set and not SetDelayed for the first case. Using your example:
Put[x^2, "test.m"];
g[x_] = Get["test.m"];
g[2]
4
This is not unique to Put/Get. Anytime you need to evaluate an expression and then convert it to a “function”, I find using Set (=), to be more clear than trying to deal with Holding, etc.
As to your second example, I would consider using Save[] or DumpSave[] to save your procedure. For example:
Great, this works. Meanwhile I also found a solution with packages but this is even simpler. Now, my codes will get much shorter.
Thank you very much, Neil.