Is it possible to define a default argument value based on the function's internal variables at the moment of return?

Would it possible and appropriate for Julia to extend functionality of function definitions to include ones like this?

function f(x, z = y^2)
    y = 2x
    return x + y + z
end

It would need to evaluate the default value of z as the (second) last command for the function f since the value of its dependent variable y could get changed anytime during the function call.

Is it possible and appropriate to design such functionality? I feel like there may be potential clashes somehow (which I haven’t been able to think of yet, but maybe something like default interdependent variables e.g. function g(x, z = 2y, y = 3z) ... end) but those could be parsed as errors.

function f(x, z = nothing)
   y = 2x
   tmp = z === nothing ? y^2 : z
   return x + y + tmp
end

Because y only exists in the function body, it can’t be used in the default arguments. Default arguments can depend on other arguments though:

julia> f(a, b=2a) = b
f (generic function with 2 methods)

julia> f(1)
2
5 Likes

Also, if you are OK with keyword arguments and y visible to the user, you can do

f(x; y = 2*x, z = abs2(y)) = x + y + z
f(x)
f(x; z = 3)
5 Likes