5
$\begingroup$

Here's my code:

Options[f] = {"Func" -> Exp};

f[x_, OptionsPattern[]] := OptionValue["Func"][x]

f[2, "Func" -> (# + 2) &]

I expected to get 4 as a return. Instead, it doesn't evaluate anything and returns

f[0, "Func" -> #1 + 2 &]

And the funny thing is that it works just fine when the option is a built-in function instead of a pure function:

Options[f] = {"Func" -> Exp};

f[x_, OptionsPattern[]] := OptionValue["Func"][x];

f[2, "Func" -> Abs]
2

Can someone explain what's wrong with my code?

New contributor
Lucas Amaral is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
$\endgroup$
2
  • $\begingroup$ People often make errors like this when passing pure functions to plotting functions. For instance, feeding something like ColorFunction -> Hue[# + 1/2] & or RegionFunction -> 2 < #1^2 + #2^2 < 9 & to those functions when they should have respectively been ColorFunction -> (Hue[# + 1/2] &) or RegionFunction -> (2 < #1^2 + #2^2 < 9 &). $\endgroup$ – J. M.'s ennui 11 hours ago
  • $\begingroup$ For completeness, here's the entire operator precedence table. Instead of learning it by heart, using repeated Ctrl-. keypresses you can select progressively wider areas of a command, which makes operator precedence obvious. See "Extend Selection" on the Keyboard Shortcut Listing. $\endgroup$ – Roman 10 hours ago
8
$\begingroup$

Use f[2, "Func" -> (# + 2) &] // FullForm to discover that operator precedence has bitten you. You have written effectively ("Func" -> #1 + 2) &, not "Func" -> ((#1 + 2)&).

By the way, the other shorthand for Function, namely f[2, "Func" -> x \[Function] x + 2], also fails, but with a much more explicit message: "Parameter specification Func->x in Function[Func->x,x+2] should be a symbol or a list of symbols."

$\endgroup$
1
  • 2
    $\begingroup$ Yeah, when passing functions as arguments, I usually prefer the verbose form Function[...] because of this. $\endgroup$ – Sjoerd Smit 11 hours ago

Your Answer

Lucas Amaral is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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