# Using a pure function as an option of a function

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?

• 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 &). – J. M.'s torpor Feb 26 at 14:37
• 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. – Roman Feb 26 at 15:04

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."
• Yeah, when passing functions as arguments, I usually prefer the verbose form Function[...] because of this. – Sjoerd Smit Feb 26 at 13:52