What is the best / cleanest / advisable way to test if a value is Null in Mathematica ? And Not Null?
For example:
a = Null
b = 0;
f[n_] := If[n == Null, 1, 2]
f[a]
f[b]
has the result:
1
If[0 == Null, 1, 2]
Where I would have expected that 2 for f[b].
As pointed out by Daniel (and explained in Leonid's book) Null == 0
does not evaluate to either True
or False
, so the If
statement (as written) also does not evaluate.
Null
is a special Symbol
that does not display in output, but in all other ways acts like a normal, everyday symbol.
In[1]:= Head[Null]
Out[1]= Symbol
For some undefined symbol x
, you don't want x == 0
to return False
, since x
could be zero later on. This is why Null == 0
also doesn't evaluate.
There are two possible fixes for this:
1) Force the test to evaluate using TrueQ
or SameQ
.
For the n == Null
test, the following will equivalent, but when testing numerical objects they will not. (This is because Equal
uses an approximate test for numerical equivalence.)
f[n_] := If[TrueQ[n == Null], 1, 2] (* TrueQ *)
f[n_] := If[n === Null, 1, 2] (* SameQ *)
Using the above, the conditional statement works as you wanted:
In[3]:= {f[Null], f[0]}
Out[3]= {1, 2}
2) Use the optional 4th argument of If
that is returned if the test remains unevaluated (i.e. if it is neither True
nor False
)
g[n_] := If[n == Null, 1, 2, 3]
Then
In[5]:= {g[Null], g[0]}
Out[5]= {1, 3}
Another possibility is to have two DownValues, one for the special condition Null, and your normal definition. This has the advantage that you don't need to worry about Null in the second one.
f[Null] := 1
f[x_] := x^2 (* no weird Null^2 coming out of here! *)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With