patt:def or Optional[patt,def]
is a pattern object that represents an expression of the form patt, which, if omitted, should be replaced by the default value def.
- Optional is used to specify "optional arguments" in functions represented by patterns. The pattern object p gives the form the argument should have, if it is present. The expression v gives the "default value" to use if the argument is absent.
- The form s_:v is equivalent to Optional[s_,v]. This form is also equivalent to s:_:v. There is no syntactic ambiguity since s must be a symbol in this case. »
- The special form s_. is equivalent to Optional[s_] and can be used to represent function arguments which, if omitted, should be replaced by default values globally specified for the functions in which they occur. »
- Values for Default[f,…] specify default values to be used when _. appears as an argument of f. Any assignments for Default[f,…] must be made before _. first appears as an argument of f. »
- Optional[s_h] represents a function that can be omitted, but that, if present, must have head h. There is no simpler syntactic form for this case. »
- The value k in Optional[s_h,k] need not have the head h. More generally, the default value need not match any pattern requirements for optional arguments that are actually present. »
- Functions with built‐in default values include Plus, Times and Power. »
Examplesopen allclose all
Basic Examples (1)
Properties & Relations (6)
The ternary form sym:pat:def has head Optional:
If no explicit default is given, the default is inferred from DefaultValues of the head:
Optional does not prevent the default value from evaluating:
Use HoldPattern to delay evaluation of the default value until it is used:
Define a function using BlankNullSequence; the function evaluates with no value:
Since BlankNullSequence matches a zero argument length, the form x___:d will never use d:
Possible Issues (3)
If s is a symbol, then s:v represents Pattern[s,v]:
Instead, apply the test to the first argument of Optional:
Instead, put the pattern inside the first argument to Optional:
Note that the Optional object can written more compactly using the ternary form s:p:d:
Wolfram Research (1988), Optional, Wolfram Language function, https://reference.wolfram.com/language/ref/Optional.html (updated 2015).
Wolfram Language. 1988. "Optional." Wolfram Language & System Documentation Center. Wolfram Research. Last Modified 2015. https://reference.wolfram.com/language/ref/Optional.html.
Wolfram Language. (1988). Optional. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/Optional.html