I'm trying to make sense of the syntax in the clause opts:OptionsPattern[]
, as found in this standard "rule-based" (pseudo-)function definition pattern:
aFunction[a1_, a2_, a3_, opts:OptionsPattern[]] := ...
I've spent the last couple of hours chasing one reference after another in the Mathematica documentation, and getting nowhere. In fact, I now have a few more questions than the ones I began with (and remain unanswered).
Let me try to distill all these questions into two.
First, does :
have a unique, consistent interpretation? If it does I can't figure it out. It seems to have a completely different meaning depending on the context. Here's a stark illustration: suppose that a
, b
, c
, and d
are unbound symbols. Then, of the following expressions, the first three are valid, but the last one is not (i.e. the front end throws an exception):
b : c : d
b :(c : d)
a :(b : c): d
(b : c): d
I was not prepared for this! (At worst, I expected non-associativity, as found with the -
or /
operators, for example; IOW, at worst I expected that (b:c):d
would be merely different from b:(c:d)
, not that it would throw an exception.)
Second, is the syntax of opts:OptionsPattern[]
aFunction[a1_, a2_, a3_, opts:OptionsPattern[]] := ...
a special form (i.e. not deducible from any other syntactic rule in the language)? It appears so to me, because I cannot produce any useful expressions with the symbol:defaultValue pattern among the formal arguments of a "rule-based" (pseudo-)function definition1.
So a different way to formulate the second question is: is there any useful application of the form
aFunction[..., symbol:defaultValue] := ...
...in which defaultValue is something other than OptionsPattern[]
?
Note: I know the use-case for the similar-looking form (note the _
)
aFunction[..., symbol_:defaultValue] := ...
I'm not asking about it.
1 For example:
foo[x:8] := x;
foo[]
(* foo[] *)
foo[3]
(* foo[3] *)
Contrast the "do-nothing" definition above with this one:
frobozz[x:OptionsPattern[]] := x;
frobozz[]
(* Sequence[] *)
frobozz[1]
(* frobozz[1] *)
frobozz[quux->frobnitz]
(* quux->frobnitz *)
OptionPattern
has non-standard semantics and colon ( : ) has context sensitive semantics. $\endgroup$a:b:c
, the uses are in fact different. the one on the left gives a name to a pattern. The one on the right gives it an optional value. I agree there is a semblance to context sensitivity and I also am not so happy with that. To see it more starkly, compare these three:FullForm[a : b]
,FullForm[_ : b]
, andFullForm[a : b : c]
. The "colon-b" parsing is not, strictly speaking, context sensitive. But it sure tries its best to be coy about that fact. Finicky too, about when it will even parse: checkFullForm[c[a] : b]
. $\endgroup$Log[Exp[y]]
has ever seemed too pedagogical for you, maybe the definitionlog[y:Exp[x_]] := x
could be useful? $\endgroup$