# Hiding variable names in function definitions

I have a problem where Table and similar functions' substitution variable name can conflict with names in my function it self. Here's a minimal example

foo[a_] :=
Probability[x > 0, x \[Distributed] NormalDistribution[a, 1]]


if i execute

foo[-1]//N


I get the correct answer (0.158655).

if I execute instead (or use Table or similar)

foo[x] /. x->-1


I get 0 because the substitution operator substitutes x into the Probability arguments too making foo become Probability[-1>0,....

The obvious "fix" is to just not use the same variable but then I have to remember how i've defined every function I've written and if I forget i risk making a mistake that may or may not be obvious.

One way around this could be to make local x inside your module. Like this

foo[a_] := Module[{x},
Probability[x > 0, x \[Distributed] NormalDistribution[a, 1]]]


And now you can do

foo[-1] // N


And

foo[x] /. x -> -1


This is the purpose of Formal Symbols. They are special symbols that can not be set to a value so that they will not clash with variables in your code. For formal lowercase x you enter Esc\$xEsc.

foo[a_] :=
Probability[\[FormalX] > 0, \[FormalX] \[Distributed] NormalDistribution[a, 1]]


Which looks like the image below in a notebook.

With this the variable x can be set a value and it will not clash with \[FormalX] in foo.

x = 5;
foo[0]

1/2


Hope this helps.

• This is a good feature to know about, but it appears that they can be subject to substitution rules. From you link: "Specific values for formal symbols can be substituted using replacement rules." – user1816847 Sep 14 at 23:43
• @user1816847 Of course they can be replaced by Replace* functions. Under what condition would you expect a replacement not to replace? – Edmund Sep 14 at 23:51