Testing for Null and not Null in Mathematica

我只是一个虾纸丫 提交于 2019-12-08 15:11:33

问题


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].


回答1:


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}



回答2:


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! *)


来源:https://stackoverflow.com/questions/6510289/testing-for-null-and-not-null-in-mathematica

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!