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_: #) & $\endgroup$Precedence
of operators. The problem arises from the fact thatFunction (&)
has a rather low precedence. This can be seen by running this command:Precedence /@ {Pattern, Optional, Function}
. $\endgroup$f[x_, func_: (# &)] := func[x]
andF[x_, func_] := func[x]
the same? $\endgroup$