8

我想做类似的事情

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有很多选项的情况下。

4

2 回答 2

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 *)

此外,如果您需要,这允许对自动值进行更复杂的解释。

于 2011-10-28T03:56:03.830 回答
4

你写了:

我想做类似的事情

foo[OptionsPattern[]] := OptionValue[b]
Options[foo] = {a -> 0, b :> OptionValue[a]};
foo[a -> 1]

并让 Mathematica 给我1,而不是0.

我得到OptionValue[a]这个回报,而不是1OR 0。这是因为OptionValue要匹配OptionsPattern[]而不是。考虑:

ClearAll[foo, a, b]
Options[foo] = {a -> 0};
foo[___] := OptionValue[a]

foo[it, doesnt, matter]
(* Out[]= OptionValue[a] *)

这是实现您的目标的一种可能方法。我命名,OptionsPattern[]以便我可以在 OptionValue 之外使用这些规则。请注意,我仍然可以为b.

ClearAll[foo, a, b]
Options[foo] = {a -> 0, b -> a};
foo[opts : OptionsPattern[]] := OptionValue[b] /. {opts}

foo[a -> 1]
foo[a -> 3, b -> 7]
1
7
于 2011-10-28T05:00:32.067 回答