3
$\begingroup$

Say I define a function f[x_, y_]:= ..., the concrete definition of which is not important now.

What is important though is, that I want x to be a real number, and y to be a boolean variable, such that it can only have value True or False.

The former I can do by f[x_Real, y_]:= ..., such as described here in the help for "patterns", under "Specifying Types of Expression in Patterns".

However there does not seem to be an equivalent boolean type. Or at least, it is not simply y_Boolean.

Does anyone know how to do this? Thanks for suggestions!

$\endgroup$
  • $\begingroup$ f[x_?NumericQ, y_?BooleanQ]:=... $\endgroup$ – Bob Hanlon Apr 8 at 17:00
  • $\begingroup$ Looks like a good alternative to the answer of Henrik, thanks! $\endgroup$ – Britzel Apr 9 at 13:10
7
$\begingroup$

Should be doable with

f[y : True | False] := ...

Beware that the pattern x_Real checks only whether the Head of x is equal to Real; it does not check whether x is a real number or not. For example, MatchQ[1, x_Real] returns False.

| improve this answer | |
$\endgroup$
  • $\begingroup$ @Hendrik Schumacher Works like a charm, thanks! Also thanks for the warning. I see what you mean. So how would I then for instance restrict x to be in the interval (0, 3), but where ideally I would also integers allowed to be entered? If this is not possible, then the restriction to the interval as float would do. $\endgroup$ – Britzel Apr 8 at 11:47
  • $\begingroup$ Then try x_?(0<#<3)&. The _? pattern means that the pattern matches only if the function following it (here: (0<#<3)&) evaluates to True. $\endgroup$ – Henrik Schumacher Apr 8 at 11:50
  • $\begingroup$ This doesn't seem to work. However it is not the most pressing issue for now. The other one was more important. Thanks again! $\endgroup$ – Britzel Apr 8 at 14:33
  • $\begingroup$ Oh, it was the closing parenthesis. Please try x_?(0<#<3&). $\endgroup$ – Henrik Schumacher Apr 8 at 15:05
  • 1
    $\begingroup$ @Britzel "how would I then for instance restrict x to be in the interval $(0, 3)$, but where ideally I would also integers allowed to be entered" - you can use Condition for this: f[x_Integer /; 0 < x < 3] := (* stuff *). $\endgroup$ – J. M.'s technical difficulties May 16 at 8:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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