4
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ What error do you get? Can you add some sample use which leads to an error? $\endgroup$ – Leonid Shifrin Dec 6 '12 at 19:21
  • $\begingroup$ @LeonidShifrin: "Options::tag: Rule for Options of Options[DateString] can only be attached to DateString." $\endgroup$ – orome Dec 6 '12 at 19:31
  • $\begingroup$ I dont see why do you need that definition at all (the one with Options). The following input, for example, works without a problem: DateString[zoned[{1959, 8, 29, 0, 0, 0}], {"Year"}, ShowZone -> True]. $\endgroup$ – Leonid Shifrin Dec 6 '12 at 19:46
  • 1
    $\begingroup$ Then we are back to my original request: please add an example illustrating the error. Generally, it is a good practice to provide fully self-contained description, not to make us guess the missing parts. $\endgroup$ – Leonid Shifrin Dec 6 '12 at 19:53
  • 1
    $\begingroup$ @LeonidShifrin: I can't reproduce it in a clean kernel either. I'll have to look through the execution and see what happens in the context where I get this error. I've made no assignments involving DateString, zoned, or ShowZone up to that point, so I'm puzzled; but I'll see what I can uncover. $\endgroup$ – orome Dec 7 '12 at 15:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.