2
$\begingroup$

I want to define a function which can take only integer arguments and have found two ways to do the same :

func1[n_Integer, m_Integer] := If[n==m,0,n-m]
func2[n_?IntegerQ, m_?IntegerQ] := If[n==m,0,n-m]

I have also read about the difference between the two : here. Both of the above ways ensure that the functions are not evaluated if the argument is not having a Head as Integers.

However, I would like the functions to return 0 if the arguments are not integers instead of being unevaluated. One way to do this would be using a nested-if (not sure about the terminology in Mathematica) :

func3[n_, m_] := 
 If[IntegerQ[n] && IntegerQ[m], If[n == m, 1, n - m], 0]

Is there any way other than using the above to achieve the same result? Also, if I use func1 and func2 in an integral etc such that their arguments are [5,5.2] then am I going to receive any warning of the non-evaluation or that particular value is just going to be skipped?

$\endgroup$
1
  • 1
    $\begingroup$ Is there any need for the If statement? Adapting the answer by bill s, maybe: f[n_?IntegerQ, m_?IntegerQ] := n-m; f[n_, m_] := 0; f[n_?IntegerQ, n_?IntegerQ] := 0; $\endgroup$
    – user1066
    May 11, 2020 at 18:36

1 Answer 1

5
$\begingroup$

Extend the definition of your function to include all inputs:

func2[n_?IntegerQ, m_?IntegerQ] := If[n==m,0,n-m]
func2[n_, m_] := 0

Now when you input n and m integers the top definition applies, when n or m are not integers, the bottom applies. Thus func2[4, 7] is -3 while func2[54., 32] is 0. You could do the same for func1.

$\endgroup$
4
  • $\begingroup$ Nice. Before I accept this as an answer, can you also point out any pitfalls of this method? Any implementation I should be careful about? Which method is better : nested-if or extending the definition ? $\endgroup$
    – Nitin
    May 11, 2020 at 18:22
  • 1
    $\begingroup$ I'm not sure it's a pitfall, but you might want to note that func2[n_,m_] as above evaluates for symbols as well as numbers. If you don't want this, then you can extend the idea to as many different definitions as make sense for your problem. $\endgroup$
    – bill s
    May 11, 2020 at 18:33
  • 2
    $\begingroup$ To avoid premature evaluation, use func2[n_?IntegerQ, m_?IntegerQ] := n - m; func2[n_, m_?(NumericQ[#] && ! IntegerQ[#] &)] = 0; func2[n_?(NumericQ[#] && ! IntegerQ[#] &), m_] = 0; $\endgroup$
    – Bob Hanlon
    May 11, 2020 at 18:57
  • $\begingroup$ Perfect. Thank you. These helped a lot. :) $\endgroup$
    – Nitin
    May 11, 2020 at 19:48

Your Answer

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

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