Optional named arguments without wrapping them all in “OptionValue”

后端 未结 3 2125
星月不相逢
星月不相逢 2020-12-30 15:56

Suppose I have a function with optional named arguments but I insist on referring to the arguments by their unadorned names.

Consider this function that adds its two

3条回答
  •  轮回少年
    2020-12-30 16:19

    Here is the final version of my answer, containing the contributions from the answer by Brett Champion.

    ClearAll[def];
    SetAttributes[def, HoldAll];
    def[lhs : f_[args___] :> rhs_] /; !FreeQ[Unevaluated[lhs], OptionsPattern] :=
       With[{optionNames = Options[f][[All, 1]]},
         lhs := Block[optionNames, optionNames = OptionValue[optionNames]; rhs]];
    def[lhs : f_[args___] :> rhs_] := lhs := rhs;
    

    The reason why the definition is given as a delayed rule in the argument is that this way we can benefit from the syntax highlighting. Block trick is used because it fits the problem: it does not interfere with possible nested lexical scoping constructs inside your function, and therefore there is no danger of inadvertent variable capture. We check for presence of OptionsPattern since this code wil not be correct for definitions without it, and we want def to also work in that case. Example of use:

    Clear[f, a, b, c, d];
    Options[f] = {a -> c, b -> d};
    (*The default values.*)
    def[f[n_, OptionsPattern[]] :> (a + b)^n]
    

    You can look now at the definition:

    Global`f
    f[n$_,OptionsPattern[]]:=Block[{a,b},{a,b}=OptionValue[{a,b}];(a+b)^n$]
    
    f[n_,m_]:=m+n
    
    Options[f]={a->c,b->d}
    

    We can test it now:

    In[10]:= f[2]
    Out[10]= (c+d)^2
    
    In[11]:= f[2,a->e,b->q]
    Out[11]= (e+q)^2
    

    The modifications are done at "compile - time" and are pretty transparent. While this solution saves some typing w.r.t. Brett's, it determines the set of option names at "compile-time", while Brett's - at "run-time". Therefore, it is a bit more fragile than Brett's: if you add some new option to the function after it has been defined with def, you must Clear it and rerun def. In practice, however, it is customary to start with ClearAll and put all definitions in one piece (cell), so this does not seem to be a real problem. Also, it can not work with string option names, but your original concept also assumes they are Symbols. Also, they should not have global values, at least not at the time when def executes.

提交回复
热议问题