Optional named arguments in Mathematica

后端 未结 3 475
野性不改
野性不改 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:24

    I found the standard way to do it in the Mathematica documentation: http://reference.wolfram.com/mathematica/tutorial/SettingUpFunctionsWithOptionalArguments.html

    Options[foo] = {a->1, b->2, c->3};  (* defaults *)
    foo[OptionsPattern[]] := bar[OptionValue@a, OptionValue@b, OptionValue@c]
    

    Typing "OptionValue" every time is a little cumbersome. For some reason you can't just make a global abbreviation like ov = OptionValue but you can do this:

    foo[OptionsPattern[]] := Module[{ov},
      ov[x___] := OptionValue[x];
      bar[ov@a, ov@b, ov@c]]
    

    Or this:

    With[{ov = OptionValue},
      foo[OptionsPattern[]] := bar[ov@a, ov@b, ov@c]
    ]
    

    Or this:

    $PreRead = ReplaceAll[#, "ov" -> "OptionValue"] &;
    
    foo[OptionsPattern[]] := bar[ov@a, ov@b, ov@c]
    

提交回复
热议问题