测试一个表达式是否是一个函数?
函数 FunctionQ
会是什么样子,也许我什至可以指定允许的参数数量?
How would a function FunctionQ
look like, maybe in a way I can even specify the number of arguments allowed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在西蒙和丹尼尔之后发帖我真的感觉很糟糕,但是他们的代码在非函数(不是符号)上失败了。按照 Simon 的建议,通过
NumericFunction
检查这一点并添加对内置函数的检查,我们得到了类似的东西,它应该在某些(叹气)现实世界的情况下工作
如果你知道函数的签名,你正在寻找(即有多少个参数以及什么类型),我同意 Simon 的观点,即方法是鸭子类型:将函数应用于典型参数,并查找有效输出。缓存可能是值得的:
I really feel bad posting after Simon and Daniel, but their codes fail on non-functions which are not symbols. Checking for that and adding a check for builtins via
NumericFunction
, as suggested by Simon, we arrive at something likewhich should work in some (sigh) real-world cases
If you know the signature of the function you are looking for (i.e. how many arguments and of what type), I would agree with Simon that the way to go is duck typing:
Apply
the function to typical arguments, and look for valid output. Caching might be worthwhile:正如丹尼尔所说,他的测试(可能应该是这样)
既快速又肮脏。对于内置函数,它将失败,例如
FunctionQ[Sin]
将返回 False (许多内置函数将通过检查Attribute
NumericFunction
来捕获代码>)。对于f[x_][y_]
等,它也会失败......它可能还应该测试UpValues
、SubValues
以及也许 < code>NValues (请参阅此处了解其含义) 。此问题已在此 中讨论线程。这个线程中有许多有用的想法 - 例如找到某些函数可以采用的参数数量的方法,但讨论中没有达成真正的共识。
我认为最好的方法是鸭子打字。您可能知道您希望函数采用多少个参数以及什么类型的参数,因此请使用 价值Q。然后确保使用 Check 捕获错误。
编辑:
另一个 comp.soft-sys.math.mathematica
As Daniel said, his test (which probably should read)
Is quick and dirty. It will fail for built in functions, e.g.
FunctionQ[Sin]
will return False (Many built-in functions will be caught by checking for theAttribute
NumericFunction
). It will also fail for things likef[x_][y_]
etc... It should probably also testUpValues
,SubValues
and maybeNValues
(see here for their meanings).This problem was discussed in this thread. Many useful ideas are in this thread - eg ways to find the number of arguments that some functions can take, but there was no real consensus reached in the discussion.
I think that the best approach is a kind of duck typing. You probably know how many and what type of arguments you want your function to take, so test it with ValueQ. Then make sure that you catch errors using Check.
EDIT:
Another comp.soft-sys.math.mathematica thread.
这是一些快速而肮脏的东西,可能会满足您的需要:
Here's something quick and dirty which may do what you need: