Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
share|improve this question

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.

up vote 7 down vote accepted

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] *)
share|improve this answer

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