Is there any way to use the head of Integer and Real together like below? The below is not right, I know that, it is just for showing my thought.
f[x_(Integer||Real)] := x^2
The reason I ask this is because I need a function that receives an argument which is either integer or real.
Answer
To match your literal request you need Alternatives rather than Or.
Either x : (_Integer | _Real) or x_Integer | x_Real will work.
Following what Szabolcs and "Guess who it is" wrote you might define a realQ like so:
realQ = NumericQ[#] && Im[#] == 0 &;
f[x_?realQ] := x^2
f /@ {1, Pi, 1.3, 2/3, x^2, 7.1 - 2.8 I}
{1, π^2, 1.69, 4/9, f[x^2], f[7.1 - 2.8 I]}
Of note for those who are comfortable using undocumented functions:
Internal`RealValuedNumericQ /@ {1, Pi, 1.3, 2/3, x^2, 7.1 - 2.8 I}
{True, True, True, True, False, False}
There is also Internal`RealValuedNumberQ which passes only explicit numbers:
Internal`RealValuedNumberQ /@ {1, Pi, 1.3, 2/3, x^2, 7.1 - 2.8 I}
{True, False, True, True, False, False}
Comments
Post a Comment