6
$\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?

$\endgroup$
2
  • 1
    $\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 torpor Feb 26 at 14:37
  • 1
    $\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 Feb 26 at 15:04
10
$\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 Feb 26 at 13:52

Your Answer

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.