Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

add comment

1 Answer 1

up vote 6 down vote accepted

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

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