# Don't pollute outside context when solving equation from the outside

This code works fine only if a is not defined in the outside context:

getA[f_,total_]:=Module[{},
result=Solve[\!$$\*SubsuperscriptBox[\(\[Integral]$$, $$0$$, $$255$$]$$f \[DifferentialD]i$$\)==total,a];
If[Length[result] == 0,Return[False]];
a/.First@result//N
];
plotShow[f_,max_]:=Module[{},
a=getA[f,max];
If[!a,Return[]];
Print[f];
Plot[f,{i,0,255}]
];

plotShow[i * a, 3500] (* => 0.107651 i      & a plot*)
(* Now showPlot has polluted the outside context with a = 0.107651 *)
plotShow[i * a, 3500] (* => Solve::ivar: "0.107651 is not a valid variable." *)


How can I make the function plotShow stop polluting the outside context?

-
@PinguinDirk Yes that fixed it, thank you! – Tyilo May 3 '13 at 9:46
(I commented to repleace plotShow[f_,max_]:=Module[{},...] by plotShow[f_,max_]:=Block[{a},...] - this is ok only as long as a is empty) – Pinguin Dirk May 3 '13 at 9:48

As in my comment above, here's a way that works even if a and/or i have global values:

getA[f_, total_] := Module[{result},
result = Solve[Integrate[f[a, i], {i, 0, 255}] == total, a];
If[Length[result] == 0, Return[False]];
a /. First@result // N
];

plotShow[f_, max_] := Block[{a, i},
a = getA[f, max];
If[! a, Return[]];
Print[f[a, i]];
Plot[f[a, i], {i, 0, 255}]
];

f[a_, i_] := i a
plotShow[f, 3500]


I tried not to modify most of your code, just the Block is new and so is the declaration of f. I hope this helps (note that there are many threads here discussing Module vs. Block)

-