f::badargs = "A single argument of type integer was expected";
f[x_Integer] := x^2;
f[args___] := "dummyString" /; Message[f::badargs];
Then for non-integer input I get:
In[58]:= f[.2]
During evaluation of In[58]:= f::badargs: A single argument of type integer was expected
Out[58]= f[0.2]
Is there a way to print the message, but prevent the f[0.2] from printing? I’m using a similar approach for a case where argument is a massive list…that I do not want printed out.
Any help is much appreciated.
f::badargs = "A single argument of type integer was expected";
f[x_Integer] := x^2;
f[args___] := Message[f::badargs];
Of course, then the unevaluated form isn’t returned. Option 2: Use FormatValues. Something like
In[55]:= f::badargs = "A single argument of type integer was expected";
f[x_Integer] := x^2;
f[args___] := "dummy" /; Message[f::badargs];
Format[HoldPattern[f[x : Except[_Integer]]]] := Null;
Format[HoldPattern[f[]]] := Null;
Format[HoldPattern[f[_, __]]] := Null
In[61]:= f[.2]
During evaluation of In[61]:= f::badargs: A single argument of type
integer was expected
Out[61]= Null
There is a serious problem with your implementation that should be pointed out: you put the Message call into a pattern test. This means that Message[] may get evaluated even if the corresponding definition of f[] isn’t.
Suppose that you add the following additional definition to f[]:
f[x_] /; x < 0 := x^3
In this case f[-0.1] will still issue the message.
The correct way to do it is to put Message[] in the body of the function, so it only gets evaluated when the corresponding pattern does match: