How to avoid collision between optional arguments and options
Mathematica has to be able to tell that the default arguments can't be rules. So, for some special cases, you could do
Options[f] = {"g" -> Identity};
f[x_, y_Integer: 2, z_Integer: 3, OptionsPattern[]]:= OptionValue["g"][x + y + z]
Testing:
f[1, 2, 3, "g" -> (#^2 &)]
36
f[1]
6
f[1, "g" -> (#^2 &)]
36
Edit: better answer below.
I voted for Rojo's answer. If for some reason you cannot be that specific about your arguments you might use the converse:
nr = Except[_?OptionQ];
f[x_, y : nr : 2, z : nr : 3, OptionsPattern[]] := OptionValue["g"][x + y + z]
If for some further reason you need the optional arguments to be rules themselves, you could filter out specifically valid options:
Options[f] = {"g" -> Identity};
notOpts =
Except[Alternatives @@ Replace[Options[f], h_[a_, _] :> h[a, _], 1]];
f[x_, y : notOpts : 2, z : notOpts : 3, OptionsPattern[]] :=
{OptionValue["g"], x, y, z}
f[1, "a" -> 7, "g" -> "g value"]
{"g value", 1, "a" -> 7, 3}
Here is another method that I learned through reading Inside the Mathematica Pattern Matcher:
Options[f] = {"g" -> Identity};
f[x_,
Shortest[y_: 2, 1],
Shortest[z_: 3, 2],
OptionsPattern[]
] := OptionValue["g"][x + y + z]
From the documentation for Shortest
:
Shortest[p, pri] is given priority pri to be the shortest sequence. Matches for shortest sequences are tried first for Shortest objects with higher priorities.