Mathematica中的可选命名参数

dre*_*ves 12 wolfram-mathematica function named-parameters

使用可选的命名参数定义函数的最佳/规范方法是什么?为了使混凝土,让我们创建一个函数foo与命名的参数a,bc,其默认为1,2,3,分别.为了比较,这是一个foo带位置参数的版本:

foo[a_:1, b_:2, c_:3] := bar[a,b,c]
Run Code Online (Sandbox Code Playgroud)

以下是命名参数版本的示例输入和输出foo:

foo[]                  --> bar[1,2,3]
foo[b->7]              --> bar[1,7,3]
foo[a->6, b->7, c->8]  --> bar[6,7,8]
Run Code Online (Sandbox Code Playgroud)

当然,在命名参数之前使用位置参数也很容易.

dre*_*ves 12

我在Mathematica文档中找到了标准方法: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]
Run Code Online (Sandbox Code Playgroud)

每次输入"OptionValue"都有点麻烦.出于某种原因,你不能只是制作全局缩写,ov = OptionValue但你可以这样做:

foo[OptionsPattern[]] := Module[{ov},
  ov[x___] := OptionValue[x];
  bar[ov@a, ov@b, ov@c]]
Run Code Online (Sandbox Code Playgroud)

或这个:

With[{ov = OptionValue},
  foo[OptionsPattern[]] := bar[ov@a, ov@b, ov@c]
]
Run Code Online (Sandbox Code Playgroud)

或这个:

$PreRead = ReplaceAll[#, "ov" -> "OptionValue"] &;

foo[OptionsPattern[]] := bar[ov@a, ov@b, ov@c]
Run Code Online (Sandbox Code Playgroud)


Jan*_*nus 6

是的,OptionValue可能有点棘手,因为它依赖于一块魔法

OptionValue[name]相当于OptionValue[f,name],其中出现f的转换规则的左侧的头部在哪里OptionValue[name].

投入一个明确的Automatic通常是诀窍,所以在你的情况下我会说解决方案是:

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

顺便说一句,选项通过匹配来完成opts:___?OptionQ,然后手动查找选项值{a,b,c}/.Flatten[{opts}].模式检查OptionQ仍然存在(虽然未记录),但该OptionValue方法的优点是您可以获得不存在选项的警告(例如foo[d->3]).这也是您第二次回复的情况,但不适用于您接受的回复.