Defining a function that modifies its argument in place defines a new function instead

Hello! I have the following function

using SpecialFunctions
function CDFFoldedNormal(x,μ,σ)
    #follow the example: https://en.wikipedia.org/wiki/Folded_normal_distribution
    #Note that the folded normal is NOT the half normal (unless μ=0)

    term1 = erf((x+μ)/(sqrt(2)*σ));
    term2 = erf((x-μ)/(sqrt(2)*σ));

    return 0.5 * (term1 + term2);
end

which is part of the following function that is supposed to modify its argument:

function foo!(F,x) 
    F = CDFFoldedNormal(x,0.03,0.05) - 0.95;
end

When I try to evaluate the function that modifies its argument in-place, like so

F = 0.
foo!(F,0.105)

Instead of getting F as a modified argument. I get F as a redefined function and the error message invalid redefinition of constant Main.F

Could someone please help me rewrite the function foo! so that it modifies its argument in-place?

Thank you!

That’s probably related to some previous definition of F in your section. Maybe you can get rid of it by restarting Julia.

If the output is a scalar, you cannot modify it “in place”, because it is immutable. Instead, you have to reassign the value bound to F:

julia> F = 0.0
0.0

julia> F = foo!(F, 0.105)
-0.02027417507189877

julia> F
-0.02027417507189877
1 Like

To be clear, this error is being thrown at F = 0. The F = CDF... assigns a local F in foo!, it doesn’t reassign Main.F. Reassignments of variables are different from in-place mutation of instances.