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].

  • $\begingroup$ 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! $\endgroup$
    – Michael E2
    Sep 10, 2016 at 2:01

2 Answers 2

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



fun[5, g]


fun[5, 2 # &]


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, Sqrt]

42 + Sqrt[42]


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.