Optional named arguments in Mathematica

后端 未结 3 464
野性不改
野性不改 2021-02-04 10:33

What\'s the best/canonical way to define a function with optional named arguments? To make it concrete, let\'s create a function foo with named arguments a

3条回答
  •  情书的邮戳
    2021-02-04 11:17

    Yes, OptionValue can be a bit tricky because is relies on a 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.

    Throwing in an explicit Automatic usually does the trick, so in your case I would say that the solution is:

    Options[foo] = {a -> 1, b -> 2, c -> 3};
    foo[OptionsPattern[]] := 
      bar @@ (OptionValue[Automatic, #] &) /@ First /@ Options[foo] 
    

    By the way, options used to be done by matching to opts:___?OptionQ, and then finding option values manually as {a,b,c}/.Flatten[{opts}]. The pattern check OptionQ is still around (although not documented), but the OptionValue approach has the advantage that you get warnings for non-existing options (e.g. foo[d->3]). This would also be the case for your second response, but not for the one you have accepted.

提交回复
热议问题