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 eitherTrue
orFalse
, so theIf
statement (as written) also does not evaluate.Null
is a specialSymbol
that does not display in output, but in all other ways acts like a normal, everyday symbol.For some undefined symbol
x
, you don't wantx == 0
to returnFalse
, sincex
could be zero later on. This is whyNull == 0
also doesn't evaluate.There are two possible fixes for this:
1) Force the test to evaluate using
TrueQ
orSameQ
.For the
n == Null
test, the following will equivalent, but when testing numerical objects they will not. (This is becauseEqual
uses an approximate test for numerical equivalence.)Using the above, the conditional statement works as you wanted:
2) Use the optional 4th argument of
If
that is returned if the test remains unevaluated (i.e. if it is neitherTrue
norFalse
)Then
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.