Wolfram mathematica 如何获得相互依赖的选项?
我想做一些像Wolfram mathematica 如何获得相互依赖的选项?,wolfram-mathematica,options,optional-parameters,optional-values,Wolfram Mathematica,Options,Optional Parameters,Optional Values,我想做一些像 foo[OptionsPattern[]] := OptionValue[b] Options[foo] = {a -> 0, b :> OptionValue[a]}; foo[a -> 1] foo[OptionsPattern[]] := OptionValue[b] Options[foo] = {a -> 0, b :> OptionValue[a]}; foo[a -> 1] 让Mathematica给我1,而不是0。有比这更好的
foo[OptionsPattern[]] := OptionValue[b]
Options[foo] = {a -> 0, b :> OptionValue[a]};
foo[a -> 1]
foo[OptionsPattern[]] := OptionValue[b]
Options[foo] = {a -> 0, b :> OptionValue[a]};
foo[a -> 1]
让Mathematica给我1
,而不是0
。有比这更好的方法吗
foo[OptionsPattern[]] := (
Options[foo] = {a -> 0, b :> OptionValue[a]};
OptionValue[b]
)
foo[a -> 1]
?
首先,在每次通话中设置
foo
的选项效率很低,特别是如果foo
有很多选项的话。这就是为什么我们有自动
。我会使用类似于:
Options[foo] = {a -> 0, b -> Automatic};
foo[OptionsPattern[]] :=
Block[{a, b},
{a, b} = OptionValue[{a, b}];
If[b === Automatic, a, b]
]
foo[]
(* --> 0 *)
foo[a -> 1]
(* --> 1 *)
foo[a -> 1, b -> 2]
(* --> 2 *)
此外,如果需要,还可以对自动值进行更复杂的解释。您写道:
我想做一些像
foo[OptionsPattern[]] := OptionValue[b]
Options[foo] = {a -> 0, b :> OptionValue[a]};
foo[a -> 1]
foo[OptionsPattern[]] := OptionValue[b]
Options[foo] = {a -> 0, b :> OptionValue[a]};
foo[a -> 1]
让Mathematica给我1
,而不是0
我得到的是OptionValue[a]
作为此操作的回报,而不是1
或0
。这是因为OptionValue
要与options模式[]
匹配,而不是。考虑:
ClearAll[foo, a, b]
Options[foo] = {a -> 0};
foo[___] := OptionValue[a]
foo[it, doesnt, matter]
1.
7重复问题:
1
7