5
$\begingroup$

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.

$\endgroup$
7
  • 7
    $\begingroup$ f[x_, func_: (# &)] := func[x] otherwise it is (func_: #) & $\endgroup$
    – Kuba
    Commented Oct 25, 2018 at 9:28
  • $\begingroup$ Yeah, that seems to solve it! Thanks $\endgroup$
    – Argidore
    Commented Oct 25, 2018 at 9:47
  • $\begingroup$ From all the stuff that I tried to find a solution, never thought it would be as simple as that $\endgroup$
    – Argidore
    Commented Oct 25, 2018 at 9:50
  • $\begingroup$ @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}. $\endgroup$ Commented Oct 25, 2018 at 9:56
  • $\begingroup$ Arn't the two definitions f[x_, func_: (# &)] := func[x] and F[x_, func_] := func[x] the same? $\endgroup$ Commented Oct 25, 2018 at 14:19

1 Answer 1

6
$\begingroup$

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 &;

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

f[a]
a^2

In this case, no bother with precedences of operators.

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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