2
$\begingroup$

I want to define a function with an argument, which is a list:

m = 10;
a = Table[k,{k,1,m}];
TestFun[listArg_] := Sum[listArg[[k]],{k,1,m}]

Now if I run the function,

TestFun[a]

it correctly calculates the sum to be 55.

Now I wish to define the argument of the function in such a way, that it only accepts numerical lists. For single arguments, I know this can be done for instance by:

TestFun[x_?NumericQ] := x

where x is a single number. However for lists, NumericQ returns false. I tried defining the function by

TestFun[list_?MemberQ[#,_?NumericQ]]

but that did not work. Evaluting the function now simply returns:

TestFun[{1,2,3,4,5,6,7,8,9,10}]

I'm on Version 11.

$\endgroup$
7
$\begingroup$
TestFun[listArg_?(VectorQ[#, NumericQ] &)] := Sum[listArg[[k]], {k, 1, m}]

TestFun2[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}]

55

or

TestFun2[listArg : {__?NumericQ}] := Sum[listArg[[k]], {k, 1, m}]

TestFun2[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}]

55

You can also use the following as the argument of your function:

listArg : {_?NumericQ ..}
listArg_List?(And @@ NumericQ /@ # &)
listArg_List /; (And @@ NumericQ /@ listArg)
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.