Specify an optional boolean parameter with a default value?

For an optional integer parameter I can write “y_Integer:4711”:

Clear[f];
f[x_Integer,y_Integer:4711]:=x+y;
{f[1],f[1,2]}
{4712,3}
  1. Unfortunately boolean expressions don’t have head “Boolean” but “Symbol”. Hence I cannot write “b_Boolean:True” for an optional boolean parameter with default True.

     Clear[f];
     f[x_Integer,b_Boolean:True]:=If[b,x,-x];
     {f[1],f[1,False]}
     {1,f[1,False]}
    
  2. I can write “b_?BooleanQ” or “b_/;BooleanQ[b]”. Then at least b has to be boolean, but then it is no longer optional:

     Clear[f];
     f[x_Integer,b_?BooleanQ]:=If[b,x,-x];
     {f[1],f[1,False]}
     {f[1],-1}
    
  3. I would like to write something like “b_?BooleanQ:True”. But this does not work:

     Clear[f];
     f[x_Integer,b_?BooleanQ:True]:=If[b,x,-x];
     {f[1],f[1,False]}
     {f[1],f[1,False]}
    
  4. One solution I found is with two definitions. But this is intricately and not easy to understand:

     Clear[f];
     f[x_Integer,b_?BooleanQ]:=If[b,x,-x];
     f[x_Integer,b_:True]:=f[x,b];
     {f[1],f[1,False]}
     {1,-1}
    
  5. Another solution is with “Optional”. This works, which is strange since it should be the same as within Point 3 above:

     Clear[f];
     f[x_Integer,Optional[b_?BooleanQ,True]]:=If[b,x,-x];
     {f[1],f[1,False]}
     {1,-1}
    
  6. Of course I could use “Options”, “OptionPatterns” and “OptionValue”. But this seems to be overkill to me.

  7. What is the simplest way to specify an optional boolean parameter with a default value?

This may be a way:

Clear[f];
f[x_Integer] := f[x, True];
f[x_Integer, b_ /; MemberQ[{True, False}, b]] := If[b, x, -x];

Hi Werner,

Your #3 option is close, the PatternTest has to be applied to Blank.

Clear[f];
f[x_Integer, b : (_?BooleanQ) : True] := If[b, x, -x];

{f[1], f[1, False]}
(* {1, -1} *)

Great, Rohit. That’s it. Thanks a lot.

Thanks. But this is the same as my #4