我如何获得相互依赖的选择?

Jas*_*oss 8 wolfram-mathematica options optional-parameters optional-values

我想做点什么

foo[OptionsPattern[]] := OptionValue[b]
Options[foo] = {a -> 0, b :> OptionValue[a]};
foo[a -> 1]
Run Code Online (Sandbox Code Playgroud)

让Mathematica给我1,而不是0.有没有更好的方法来做到这一点

foo[OptionsPattern[]] := (
  Options[foo] = {a -> 0, b :> OptionValue[a]};
  OptionValue[b]
)
foo[a -> 1]
Run Code Online (Sandbox Code Playgroud)

首先,foo在每次调用时设置选项都是低效的,特别是如果foo有很多选项的话.

Bre*_*ion 8

这就是我们拥有的原因Automatic.我会用以下的东西:

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 *)
Run Code Online (Sandbox Code Playgroud)

此外,如果需要,还可以对自动值进行更复杂的解释.