Mathematica中可选的命名参数 [英] Optional named arguments in Mathematica
问题描述
用可选命名参数定义函数的最佳/规范方法是什么?具体来说,让我们创建一个名为 a
, b 的函数
foo
code>和 c
,它们分别默认为1,2和3。作为比较,下面是一个带有位置参数的 foo
版本:
foo [a_:1,b_:2,c_:3]:= bar [a,b,c]
以下是 foo
命名参数版本的示例输入和输出:
foo [] - > bar [1,2,3]
foo [b-> 7] - > bar [1,7,3]
foo [a-> 6,b-> 7,c-> 8] - > bar [6,7,8]
它当然也应该很容易在命名参数。
我在Mathematica文档中找到了标准方法: http://reference.wolfram.com/mathematica/tutorial/SettingUpFunctionsWithOptionalArguments.html
选项[foo] = {a-> 1,b-> 2,c-> 3}; (* defaults *)
foo [OptionsPattern []]:= bar [OptionValue @ a,OptionValue @ b,OptionValue @ c]
每次输入OptionValue都有点麻烦。出于某种原因,您不能仅仅制作全局缩写,如 ov = OptionValue
,但您可以这样做:
foo [OptionsPattern []]:= Module [{ov},
ov [x ___]:= OptionValue [x];
bar [ov @ a,ov @ b,ov @ c]]
:
pre $ 使用[{ov = OptionValue},
foo [OptionsPattern []]:= bar [ov @ a ,ov @ b,ov @ c]
]
或者:
$ PreRead = ReplaceAll [#,ov - > OptionValue]& ;;;
foo [OptionsPattern []]:= bar [ov @ a,ov @ b,ov @ c]
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
, b
, and c
, which default to 1, 2, and 3, respectively. For comparison, here's a version of foo
with positional arguments:
foo[a_:1, b_:2, c_:3] := bar[a,b,c]
Here is sample input and output for the named-arguments version of foo
:
foo[] --> bar[1,2,3]
foo[b->7] --> bar[1,7,3]
foo[a->6, b->7, c->8] --> bar[6,7,8]
It should of course also be easy to have positional arguments before the named arguments.
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]
这篇关于Mathematica中可选的命名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!