Mathematica: How is OptionValue implemented?

The inline implementation OptionValuecontains some magic, so

OptionValue[name]equivalently OptionValue[f, name], where fis the head of the left side of the transformation rule OptionValue[name].

Does anyone have an idea how to achieve something similar for Options, i.e. implement autoOptions[], which will allow the parameters defined for the symbol on the left side of the transformation rule in which it appears autoOptions[]? For clarity, I'm looking for a way to do

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

conclusion {bar->1}

The ultimate goal is to do something like the one requested in this matter without changing anything except the RHS definition.

+5
source share
1 answer

, :

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];]

:

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

Out[10]= {bar -> 1}

, , , - , , SetDelayed, , .

+6

All Articles