1

Consider the following definition:

Options[f] = {a -> 1, b -> 2}
f[x_,OptionsPattern[]] := {x,OptionValue/@{a,b}}

I thought that doing something like f[4] would produce {4,{1,2}} but it doesn't. Instead, evaluating f[4] returns {4, {OptionValue[a], OptionValue[b]}}.

Is there a way to make OptionValue/@{a,b} produce {1, 2}? Is there a better way to achieve the same effect?

user42582
  • 4,195
  • 1
  • 10
  • 31
  • There is likely some special evaluation at play here, since {x, {OptionValue[a], OptionValue[b]}} works. – J. M.'s missing motivation Sep 08 '17 at 16:34
  • @J.M. the only member of Attributes[OptionValue] is Protected... – user42582 Sep 08 '17 at 16:39
  • it might be that OptionValue[{a,b}] works... – user42582 Sep 08 '17 at 16:41
  • 1
    Note that f[x_, OptionsPattern[]] := {x, OptionValue[f, #] & /@ {a, b}} allows f[4] to produce {4, {1, 2} }. – jjc385 Sep 08 '17 at 16:41
  • @jjc385; dully noted; edited Q – user42582 Sep 08 '17 at 16:42
  • which one is 'proper'? "@jjc385"'s comment or the answer by "@Carl Woll" – user42582 Sep 08 '17 at 16:47
  • 1
    I understand your point. A relevant question is why does OptionValue[a] work inside the definition of f without the need of OptionValue[f,a]-no need 'explaining' that we are interested in f``'s optiona`? – user42582 Sep 08 '17 at 17:06
  • 1
    See this answer, especially the second paragraph, which suggests that OptionValue is able to figure out which function it appears in only when it's given explicit arguments in the function definition (before any evaluation occurs). Actually, it turns out even f[x_, OptionsPattern[]] := {x, OptionValue[#] & /@ {a, b}} works. – jjc385 Sep 08 '17 at 17:06
  • 1
    I have marked this question as already has an answer -- please review the linked post, and if you feel that it does not address your question edit yours to specifically describe how your question or needs differ. – Mr.Wizard Sep 08 '17 at 17:27
  • @Mr.Wizard I'm good, Thanks! – user42582 Sep 08 '17 at 18:53

1 Answers1

2

Use:

Options[f] = {a -> 1, b -> 2};
f[x_,OptionsPattern[]] := {x, OptionValue[{a,b}]}

Then:

f[4]

{4, {1, 2}}

Carl Woll
  • 130,679
  • 6
  • 243
  • 355