0
$\begingroup$

Is it possible to define a function with a custom warning message ?

For example,

In[1]=  f[x_,y_]:=x-y (* with a warning message when the result is negative*)

In[2]=  f[5,3]
Out[2]= 2

In[3]=  f[3,5]
Out[3]= -2
Negative : the result is negative

Also I don't want to see duplicate warning messages. For example,

In[4]=  {f[3,7],f[4,6],f[5,7]}
Out[3]= {-4,-2,-2}
Negative : the result is negative

It produced three negative numbers, but it produced a single warning message.

$\endgroup$

1 Answer 1

3
$\begingroup$

You may e.g. use $Line:

f[x_, y_] := (If[x < y && tmp =!= $Line, 
   Print["Warning: negative result."]];
  tmp = $Line; x - y )

With this :

{f[3, 7], f[4, 6], f[5, 7]}

enter image description here

$\endgroup$
1
  • $\begingroup$ I needed some time to understsand the code. Tricky! $\endgroup$
    – imida k
    Commented Mar 22, 2021 at 9:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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