3

How can a condition and an option be written on the RHS of a function? I.e.

Clear[f, g]

(* condition on its own works fine *)

f[a_, b_Integer?Positive] := a + b

(* but doesn’t work with optional argument *)

g[a_, b_Integer?Positive : 2] := a + b
Chris Degnen
  • 30,927
  • 2
  • 54
  • 108

1 Answers1

7

You can use the following syntax to combine a pattern, pattern test and an optional value:

Clear@h
h[a_, b : _Integer?Positive : 2] := a + b

You can see from the FullForm of both syntaxes that the first one (in g) does not do what you want (i.e., is not interpreted as Optional):

b_Integer?Positive : 2 // FullForm
(* PatternTest[Pattern[b,Blank[Integer]],Pattern[Positive,2]] *)

b : _Integer?Positive : 2 // FullForm
(* Optional[Pattern[b,PatternTest[Blank[Integer],Positive]],2] *)
rm -rf
  • 88,781
  • 21
  • 293
  • 472