Optional named arguments without wrapping them all in “OptionValue”

后端 未结 3 2105
星月不相逢
星月不相逢 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:13

    Why not just use something like:

    Options[f] = {a->0, b->0};
    f[args___] := (a+b) /. Flatten[{args, Options[f]}]
    

    For more complicated code I'd probably use something like:

    Options[f] = {a->0, b->0};
    f[OptionsPattern[]] := Block[{a,b}, {a,b} = OptionValue[{a,b}]; a+b]
    

    and use a single call to OptionValue to get all the values at once. (Main reason is that this cuts down on messages if there are unknown options present.)

    Update, to programmatically generate the variables from the options list:

    Options[f] = {a -> 0, b -> 0};
    f[OptionsPattern[]] := 
      With[{names = Options[f][[All, 1]]}, 
        Block[names, names = OptionValue[names]; a + b]]
    

提交回复
热议问题