开发者

Mathematica: How is OptionValue implemented?

开发者 https://www.devze.com 2023-02-17 03:54 出处:网络
The implementation of the built-in OptionValue contains some piece of magic so that OptionValue[name] is equivalent to

The implementation of the built-in OptionValue contains some piece of magic so that

OptionValue[name] is equivalent to OptionValue[f, name], where f is the head of the left-hand side of the transformation rule in which OptionValue[name] appears.

Does anybody have an idea for how to achieve something similar for Options, i.e. implement an autoOptions[] that would resolve to the options defined for the symbol on the left hand side of the transformation rule in which autoOptions[] appears? For clarity, what I am looking for is a way to make

Options[foo]={bar->1};
foo[OptionsPattern[]]:=autoOptions[]
foo[]

output {bar-&g开发者_开发技巧t;1}

The eventual goal is to do something like requested in this question without having to change anything but the RHS of a definition.


Here is a simple, very schematic version:

Module[{tried},
  Unprotect[SetDelayed];    
  SetDelayed[f_[args___, optpt : OptionsPattern[]], rhs_] /; 
    !FreeQ[Unevaluated[rhs], autoOptions[]] :=
     Block[{tried = True},
       f[args, optpt] :=  
         Block[{autoOptions}, autoOptions[] = Options[f]; rhs]] /; ! TrueQ[tried];
  Protect[SetDelayed];]

Your usage:

In[8]:= Options[foo] = {bar -> 1};
foo[OptionsPattern[]] := autoOptions[]
foo[]

Out[10]= {bar -> 1}

Note that this won't work when explicit options are also passed - accounting for them is some more work, and this is not generally a good practice since I overloaded SetDelayed - but you asked for it and you get it.

0

精彩评论

暂无评论...
验证码 换一张
取 消