Message Boards Message Boards

1
|
3324 Views
|
2 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Suppressing part of error message output

Posted 12 years ago
If I have a simple function definition such as:
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.
POSTED BY: Porscha McRobbie
2 Replies
Two options:
Option 1:
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

doesn't prevent
In[62]:= HoldForm[f[3]]
Out[62]= \!\(
TagBox[
RowBox[{"f", "[", "3", "]"}],
HoldForm]\)

from rendering.
POSTED BY: Jeremy Michelson
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:
f[x_Integer] := x^2f[___] := (Message[f:badarg]; Null)
The Null after Message is not really necessary as Message itself returns Null, but this pattern shows how to control the value being returned.
POSTED BY: Szabolcs Horvát
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract