Defining a function which is numerical on all vectors of arguments
There is a slight problem with NumericQ
, that prevents one to define your UpValues
with it. So that would not work as expected:
f /: NumericQ[_f] := True
But manually
UpValues[f] = {HoldPattern[NumericQ[_f]] :> True};
it works as expected:
NumericQ[f[{1, 2, 3, 4}]]
NumericQ[f[1, {2}, 3, {4}]]
(* True *)
(* True *)
I thought @swish would incorporate my comment, but let me put it here, since it is an answer to the question. In the following, the arguments of f
can be numbers or any sort of nested lists of numbers.
f /: NumericQ[f[args___]] /; VectorQ[Flatten@{args}, NumericQ] := True;
NumericQ[f[1, 2, 3, 4]]
NumericQ[f[{1, 2, 3, 4}]]
NumericQ[f[1, {2}, 3, {4}]]
NumericQ[f[x]] (* False -- should check both cases T, F *)
NumericQ[f[]] (* True -- same as `NumericQ[Sin[]]` *)
(*
True
True
True
False
True
*)
Update
@pisco points out that the above does not work if f[..]
is nested inside other numeric expressions. There is an internal function that could be used to replace NumericQ
:
ClearAll[f];
Attributes@f = {NumericFunction};
Internal`WouldBeNumericQ[2 + f[1, {2}, 3], {}]
(* True *)
The last list is a list a variables, the function tests whether f
would be numeric if numeric values were substituted for the variables.