Test if an expression is a Function?

后端 未结 3 1188
不思量自难忘°
不思量自难忘° 2021-01-03 01:16

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

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-03 01:26

    As Daniel said, his test (which probably should read)

    FunctionQ[x_] := Head[x] === Function || DownValues[x] =!= {}
    

    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 the Attribute NumericFunction). It will also fail for things like f[x_][y_] etc... It should probably also test UpValues, SubValues and maybe NValues (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.

提交回复
热议问题