1
$\begingroup$

This question already has an answer here:

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?

$\endgroup$

marked as duplicate by Mr.Wizard function-construction Sep 8 '17 at 17:26

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ There is likely some special evaluation at play here, since {x, {OptionValue[a], OptionValue[b]}} works. $\endgroup$ – J. M. will be back soon Sep 8 '17 at 16:34
  • 1
    $\begingroup$ Note that f[x_, OptionsPattern[]] := {x, OptionValue[f, #] & /@ {a, b}} allows f[4] to produce {4, {1, 2} }. $\endgroup$ – jjc385 Sep 8 '17 at 16:41
  • 1
    $\begingroup$ 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 option a`? $\endgroup$ – user42582 Sep 8 '17 at 17:06
  • 1
    $\begingroup$ 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. $\endgroup$ – jjc385 Sep 8 '17 at 17:06
  • 1
    $\begingroup$ 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. $\endgroup$ – Mr.Wizard Sep 8 '17 at 17:27
2
$\begingroup$

Use:

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

Then:

f[4]

{4, {1, 2}}

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.