2
$\begingroup$

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.

$\endgroup$
8
$\begingroup$

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

Mathematica graphics

And

foo[x] /. x -> -1

Mathematica graphics

$\endgroup$
4
$\begingroup$

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.

Mathematica graphics

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.

$\endgroup$
  • $\begingroup$ 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." $\endgroup$ – user1816847 Sep 14 at 23:43
  • $\begingroup$ @user1816847 Of course they can be replaced by Replace* functions. Under what condition would you expect a replacement not to replace? $\endgroup$ – Edmund Sep 14 at 23:51

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.