# Solve variable inside Module

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?

• 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. Mar 31, 2020 at 21:34
• @Nasser: Thank you! Mar 31, 2020 at 22:06

(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.