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

marked as duplicate by Leonid Shifrin, Mr.Wizard Sep 26 '13 at 15:28

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


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

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] *)

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