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