测试表达式是否是函数? [英] Test if an expression is a Function?

查看:33
本文介绍了测试表达式是否是函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数 FunctionQ 会是什么样子,也许我什至可以指定允许的参数数量?

How would a function FunctionQ look like, maybe in a way I can even specify the number of arguments allowed?

推荐答案

在 Simon 和 Daniel 之后发帖我真的感觉很糟糕,但是他们的代码在非符号的非函数上失败.根据西蒙的建议,通过 NumericFunction 检查并添加对内置函数的检查,我们得到了类似

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 like

FunctionQ[_Function | _InterpolatingFunction | _CompiledFunction] = True;
FunctionQ[f_Symbol] := Or[
  DownValues[f] =!= {}, 
  MemberQ[ Attributes[f], NumericFunction ]]
FunctionQ[_] = False;

这应该适用于某些(叹气)现实世界的情况

which should work in some (sigh) real-world cases

In[17]:= 
FunctionQ/@{Sin,Function[x,3x], Compile[x,3 x],Interpolation[Range[5]],FunctionQ,3x,"a string", 5}
Out[17]= {True,True,True,True,True,False,False,False}

如果你知道你正在寻找的函数的签名(即有多少参数和什么类型),我同意 Simon 的看法,方法是鸭子输入:Apply 函数到典型的参数,并寻找有效的输出.缓存可能是值得的:

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:

AlternativeFunctionQ[f_]:=AlternativeFunctionQ[f]=
  With[{TypicalArgs={1.0}},NumericQ[Apply[f,TypicalArgs]]];

In[33]= AlternativeFunctionQ/@{Sin,Function[x,3x], Compile[x, 3x],Interpolation[Range[5]],FunctionQ,3x,"a string", 5}
Out[34]= {True,True,True,True,False,False,False,False} 

这篇关于测试表达式是否是函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆