How do I add options to a built in function, which only apply to a certain class of argument?-Collection of common programming errors
I’d like to add an option to a built-in function that only applies when it is given an argument of a certain form.
For example, something like this approach to extending DateString
to support an extra option when it is given a date argument that matches the form zoned[...]
(forget that zoned
does nothing here):
DateString[zoned[x_], spec_, opts : OptionsPattern[{TimeZone -> 0,ShowZone->True}]] ^:=
DateString[x, If[OptionValue[ShowZone],
Append[spec, If[OptionValue[TimeZone] != 0, "UTC" ToString[OptionValue[TimeZone]], "Z"]], spec]]
Since ShowZone
is not an option for DateString
, I get an error.
“DateString::optx: Unknown option ShowZone in DateString…”
But I can’t just associate TimeZone
as an up value for zoned
with
zoned/:Options[DateString]={ShowZone->True}
because that also results in an error:
Options::tag: Rule for Options of Options[DateString] can only be attached to DateString.
It seems I have to (unprotect DateString
and) then add a new option globally, which is generally just ignored:
Unprotect[DateString];
Options[DateString] = Union[Options[DateString], {ShowZone -> False}];
Protect[DateString];
Is this the only approach? Even this approach leaves ShowZone
blue in the function definition and red in function invocations.
Originally posted 2013-11-09 21:07:38.