# How to define a function with an optional value related to the arguments?

It's known that we can easily define a function with optional value which is not related with other arguments, but my question is how can I define a function with an optional value which is really related with other variables.

For example

fun[a_, b_:g[a]] = a + g[a]


where g[a] = a^2 is a given function. I'd like to set the optional value of b to be g[a].

• Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! – Michael E2 Sep 10 '16 at 2:01

ClearAll[fun, g]
g[x_] := x^2;
fun[a_, b_: g] := a + b[a]

fun[5]


30

fun[5, g]


30

fun[5, 2 # &]


15

fun[5, t]


5 + t[5]

Use a pure function as the optional value of the 2nd variable.

f[a_, b_:(#^2 &)] := a + b[a]

f[42]


1806

f[42, Sqrt]


42 + Sqrt[42]