The implementation of the built-in OptionValue
contains some piece of magic so that
OptionValue[name]
is equivalent toOptionValue[f, name]
, wheref
is the head of the left-hand side of the transformation rule in whichOptionValue[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.
精彩评论