本文介绍了在 Mathematica 中测试 Null 和非 Null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Mathematica 中测试值是否为 Null 的最佳/最干净/可取的方法是什么?并且不为空?

What is the best / cleanest / advisable way to test if a value is Null in Mathematica ? And Not Null?

例如:

 a = Null
 b = 0;
 f[n_] := If[n == Null, 1, 2]
 f[a]
 f[b]

有结果:

 1
 If[0 == Null, 1, 2]

我原以为 f[b] 为 2.

Where I would have expected that 2 for f[b].

推荐答案

正如 Daniel 指出的(并在 Leonid 的书中解释)Null == 0 不计算为 TrueFalse,因此 If 语句(如所写)也不求值.Null 是一种特殊的 Symbol,它不显示在输出中,但在所有其他方面都像一个普通的日常符号.

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

对于一些未定义的符号 x,你不希望 x == 0 返回 False,因为 x 以后可能为零.这就是 Null == 0 也不求值的原因.

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) 强制测试使用 TrueQSameQ 进行评估.
对于 n == Null 测试,以下内容将等效,但在测试数字对象时则不会.(这是因为 Equal 对数值等价使用近似测试.)

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) 使用 If 的可选第 4 个参数,如果测试仍然未评估(即如果它既不是 True 也不是 )

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]

然后

In[5]:= {g[Null], g[0]}
Out[5]= {1, 3}

这篇关于在 Mathematica 中测试 Null 和非 Null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 15:04