# Pure function as a variable of another function

In a notebook, I have a function that basically needs to do something like calling a pure function within a function. I would say that what best describes would be an example like:

f[x_, func_: # &] := func[x]


The problem with this is that when I use it, for example just f[x] the output is f[x] or (#1)[x] and if I call f[x, (1 + #) &] the output is (1 + #1)[x]

Even worse, if, for some reason, I decide to change the definition of f to

f[x_, func_: Exp] := func[x]


and then change it back to the original definition, the output to f[x] will now forever be Exp[x].

So, is there a way to solve this problem so that with the first definition I get the result I'm waiting f[x] = x and f[x, (1 + #) &] = 1 + x?

Thanks for the help.

• f[x_, func_: (# &)] := func[x] otherwise it is (func_: #) & – Kuba Oct 25 '18 at 9:28
• Yeah, that seems to solve it! Thanks – Argidore Oct 25 '18 at 9:47
• From all the stuff that I tried to find a solution, never thought it would be as simple as that – Argidore Oct 25 '18 at 9:50
• @Argidore There exists a concept Precedence of operators. The problem arises from the fact that Function (&) has a rather low precedence. This can be seen by running this command: Precedence /@ {Pattern, Optional, Function}. – Αλέξανδρος Ζεγγ Oct 25 '18 at 9:56
• Arn't the two definitions f[x_, func_: (# &)] := func[x] and F[x_, func_] := func[x] the same? – Ulrich Neumann Oct 25 '18 at 14:19

To specify values to a function's argument(s) which take effect when calling the function but no explicit values are going to be set to them, besides Optional (:), one can also use Default (.):
Default[f, 2] = #^2 &;

a^2