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}
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]}
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}
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]}
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}
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}
Of course I could use "Options", "OptionPatterns" and "OptionValue". But this seems to be overkill to me.
What is the simplest way to specify an optional boolean parameter with a default value?
|
|