“定义”的等价物在数学中
我需要一个函数,它将符号名称作为字符串并返回该符号是否已定义。函数 ValueQ
很接近,但它对于函数名称返回 False。此外,它需要符号而不是字符串。
示例:
defined["N"] --> True (predefined function N)
defined["x"] --> False
x = 7;
defined["x"] --> True (x is now defined)
defined["7"] --> True (7 is a number)
f[x_] := 2x
defined["f"] --> True (f has DownValues)
g[x_][y_] := x+y
defined["g"] --> True (g has SubValues)
PS:感谢 Pillsy 指出需要检查 DownValues 和 SubValues。
I need a function that takes the name of a symbol as a string and returns whether that symbol is already defined. The function ValueQ
is close but it returns False for function names. Also, it takes symbols rather than strings.
Examples:
defined["N"] --> True (predefined function N)
defined["x"] --> False
x = 7;
defined["x"] --> True (x is now defined)
defined["7"] --> True (7 is a number)
f[x_] := 2x
defined["f"] --> True (f has DownValues)
g[x_][y_] := x+y
defined["g"] --> True (g has SubValues)
PS: Thanks to Pillsy for pointing out the need to check for both DownValues and SubValues.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我将其拼凑在一起,这似乎有效:
希望有一个更漂亮的解决方案。
PS:感谢 Pillsy 指出需要检查 DownValues 和 SubValues。
I cobbled this together, which seems to work:
Hopefully there's a prettier solution.
PS: Thanks to Pillsy for pointing out the need to check for both DownValues and SubValues.
我认为名称应该可以解决问题:
如果 Names["foo"] 返回 {},则 foo 不应有定义,否则应返回 {"foo"}。
所以你的函数“定义”可能会被完成为:
至少对于符号,因为这不适用于“7”,因为 7 不是符号。您可以单独处理这种情况,例如使用 NumberQ。
此外,您还可以使用 Symbol 从字符串中创建符号(对于自动生成符号很有用),并使用 Definition 检查符号的定义。
编辑:比查看 Names 返回的内容更好,NameQ["name"] 会告诉您给定的名称是否存在。但仍然没有告诉您该符号是否有明确的定义,只是提到了它。
I think Names should do the trick:
If Names["foo"] returns {}, then there should be no definitions for foo, otherwise it should return {"foo"}.
So your function 'defined' might be done as:
For symbols at least, because this doesn't work for "7", since 7 is not a symbol. You could handle this case seperately, for instance with NumberQ.
Also, you can use Symbol to make a symbol out of a string (useful for automatically generating symbols) and Definition to check the definitions of a symbol.
EDIT: Better than looking at what Names returns, NameQ["name"] tells you if a given name exists. Still doesn't tell you if the symbol has an explicit definition though, just that it has been mentioned.
您可以使用
DownValues
来查看是否有与某个交易品种关联的“功能”。这适用于像或这样的定义,但
不适用于像这样的奇异事物
,但大多数人无论如何都不会认为这是定义函数。如果您想检查函数定义是否存在,则需要将名称转换为表达式(并确保在执行此操作时将其包含在
Hold
中!)。这是一个相当强大的函数,可以检查DownValues
和SubValues
:You can use
DownValues
to see if you have "functions" associated with a symbol. This will work for definitions likeor
It won't work for exotic things like
but most people won't think of that as defining a function anyway. If you want to check for the existence of a function definition, you need to convert the name to an expression (and make sure it's wrapped in
Hold
when you do!). Here's a reasonably robust function that checks for bothDownValues
andSubValues
: