1
$\begingroup$

Suppose I have a Module in which I use Solve[]. If I make the solve variable local, I get this:

f[a_] := Module[{soln, x},
   soln = Solve[2 x == a, {x}];
   Return[soln]
   ];
f[5]
(*{{x$117834 -> 5/2}}*)

If instead I leave the solve variable global, I get this cleaner result:

g[a_] := Module[{soln},
   soln = Solve[2 x == a, {x}];
   Return[soln]
   ];
g[5]
(*{{x -> 5/2}}*)

But if globally x has a value, x=7, this fails:

(*7 is not a valid variable*)

Why does the local variable x in the first example become x$117834? What is the best way to use variables like x in this circumstance?

$\endgroup$
  • 1
    $\begingroup$ This has been asked before many times. It is best to pass the x along with a to the module to avoid all these issues. That would be the safest method. See using-solve-in-module as an example. $\endgroup$ – Nasser Mar 31 at 21:34
  • $\begingroup$ @Nasser: Thank you! $\endgroup$ – Joseph O'Rourke Mar 31 at 22:06
3
$\begingroup$

(1) The method used by Module to emulate lexical scoping involves renaming in the way you see. Usually this is invisible because usually variables local to a Module are not explicitly returned in the result.

(2) If your variable has been assigned a value then even if you manage to get past renaming the result will still not be what you might have expected.

One way to bypass the renaming is to use Block instead of Module (Block emulates dynamic scoping by temporarily "forgetting" any values attached to the symbol).

f[a_] := Block[{soln, x},
  soln = Solve[2 x == a, {x}];
  soln]
f[5]

(* Out[68]= {{x -> 5/2}} *)

Well and good. Now assign a value to x.

x = 7;
f[5]

(* Out[70]= {{7 -> 5/2}} *)

The upshot is that it will be difficult to do this with a variable that has been assigned a value. No surprises there; this would be the case in any language.

| improve this answer | |
$\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.