# Using Solve[] in Module

Clear[x, y];
function2[eqn3_, eqn4_] :=
Module[{x, y, sol}, sol = Solve[{eqn3, eqn4}, {x, y}]; {x, y} /. sol]
function2[y == 3 x, y == x^2 - 4]


I want it to solve for x and y but this wouldnt work. I am not quite sure about how to use Solve in a Module

It is best to pass the variables to the function

function2[eqn3_, eqn4_, x_, y_] := Module[{sol},
sol = Solve[{eqn3, eqn4}, {x, y}];
{x, y} /. sol
]
function2[y == 3 x, y == x^2 - 4, x, y]


Gives

{{-1, -3}, {4, 12}}


Otherwise, different context.

When you did this

function2[eqn3_, eqn4_] := Module[{x, y, sol},
sol = Solve[{eqn3, eqn4}, {x, y}];
{x, y} /. sol
]
function2[y == 3 x, y == x^2 - 4]


Then the x,y in the equations are global context, but then you defined local x,y inside the module, which are different context (even though they look the same on the screen), they are different symbols under the cover.

• You were just a few seconds faster ;-). I propose something like systemSolver[system_List, vars_List] := Module[{sol}, sol = Solve[system, vars]; vars /. sol ] its more flexible like the OP version, but her is only duplicates Solve ;-) Mar 26, 2020 at 7:45
• This is a common problem in more general settings. Is there a general post on this issue? I think there are two problems: 1) having to input the variables and 2) having to output the solution if it contains variables. For outputting the solution one may use pure functions. See here
– Hugh
Mar 26, 2020 at 10:07