6

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.

Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
Smart Humanism
  • 507
  • 2
  • 8

2 Answers2

11

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}
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
2

I frequently write functions that take one or more arguments which I limit to those quantities that mathematicians call real numbers. In Mathematica that means any quantity satisfying NumericQ excepting complex numbers. To facilitate writing such functions, I define a pattern

validNum = Except[_Complex, _?NumericQ];

This pattern is used like so:

f[x : validNum] := x^2

Update

As Guesswhoitis points out the above is not fool-proof. A more robust version is

validNum = Except[z_ /; Head[N[z]] === Complex, _?NumericQ];
f /@ {1, 1/2, .5, Pi, 1 + I/2, 1. + .5 I, Sqrt[-1], (-1)^(2/3), E + I Pi}
{1, 1/4, 0.25, Pi^2, f[1 + I/2], f[1. + 0.5*I], f[I], f[(-1)^(2/3)], f[E + I*Pi]}
m_goldberg
  • 107,779
  • 16
  • 103
  • 257