Message Boards Message Boards

1
|
4416 Views
|
4 Replies
|
6 Total Likes
View groups...
Share
Share this post:

Specify an optional boolean parameter with a default value?

Posted 3 years ago

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?

POSTED BY: Werner Geiger
4 Replies
Posted 3 years ago

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

POSTED BY: Werner Geiger
Posted 3 years ago

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} *)
POSTED BY: Rohit Namjoshi

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];
POSTED BY: Gianluca Gorni
Posted 3 years ago

Thanks. But this is the same as my #4

POSTED BY: Werner Geiger
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract