1
$\begingroup$

I've created a try.m file which has the following structure:

{
  Hold@{a+b+c},
  Hold@{a^2+b^2}
}

On my main code I do:

Module[{a,b,c,myfile},
   a=1;
   b=2;
   c=3;
   myfile=Get["file.m"];
   ReleaseHold /@ myfile
]

note: my desired behavior would be to see the expressions in the file evaluated (linked) to the values of variables in the module. How do I do this?

Dan Reznik


my final goal is I have a very long list of algebraic expressions on a,b,c which I want to store in a file and only evaluate when needed.

@Xminer, your solution is not going to work for my case because the expressions will also use variables computed in the Block[] enviroment. I guess Block[] will work.

$\endgroup$
  • $\begingroup$ try with Rule and ReplaceAll. Module[{myfile}, rule = {a -> 1, b -> 2, c -> 3}; myfile = Get["file.m"]; ReleaseHold /@ myfile //. rule] $\endgroup$ – Xminer Jul 5 at 4:02
2
$\begingroup$

Module does not work because it scopes lexically, it replaces symbols like a with a$nnn then it evaluates the body. It should be clear now that symbols imported after that happened will not be scoped.

You can use Block because it scopes dynamically (not by replacing symbols names but by temporarily replacing given symbols definitions).

You can also skip Hold in your file.

{ {a+b+c}, {a^2+b^2} }

Block[{a = 1, b = 2, c = 3}, Get @ path]

Should be enough.

$\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.