13
$\begingroup$

Consider this

f[x_Real] := 2 x
f[1] 

f[1]

f[1.0]

2.0

I want f to be evaluated if x is an integer or real. One way can be define it twice

f[x_Real] := 2 x
f[x_Integer] := 2 x

which might not be a good idea while dealing with big functions with several variables.

Is it possible to assign multiple type (for example Real and Integer) to a single variable in a function?

$\endgroup$
1
  • 2
    $\begingroup$ Or if you want to evaluate for all numeric inputs f[x_?NumericQ] $\endgroup$
    – Bob Hanlon
    Jun 22, 2018 at 21:55

1 Answer 1

15
$\begingroup$

You may specify multiple alternative patterns (originally mentioned in a comment):

f[x:(_Real|_Integer)] := 2 x;

You may specify multiple alternative matches simultaneously:

f[(x_Real|x_Integer)] := 2 x;

You may specify by set-membership tests (Element):

f[x_?(Element[#, Reals] === True &)] := 2 x;

Note, however, that while this option will work for exceptional cases like f[Sqrt[2]], is also likely going to be quite a bit slower than any of the above.

If you are concerned not with membership in the reals but rather numeric quantities, you may use:

f[x_?NumericQ] := 2 x;

Note, however, that this will allow complex quantities. This is frequently used to prevent excessive symbolic computation with difficult functions implemented inside of other complex operations, such as Integrate.

$\endgroup$

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.