Issues with In Place Transformations and Scope

The following is a simplified and related version of the issue I raised here:

function f!(x_work, x)
    n = length(x);
    for (j,k) in zip(1:n,n:-1:1)
        x_work[j] = sin(x[k]);
    end
    x_work, x
end

function iterate_f!(x, x_work, n)
    for j in 1:n
         x, x_work = f!(x_work, x);
    end
    x, x_work
end
m = 5;
x = collect(range(0,stop=1,length=m));
x_work = zeros(m);
iterate_f!(x,x_work,1);
println(x);
println(x_work);

x = collect(range(0,stop=1,length=m));
x_work = zeros(m);
iterate_f!(x,x_work,2);
println(x);
println(x_work);

I am surprised that this appears to “fail” when the iteration is run with n=1, but works when it is called with a larger value.

I think you will find this “works” with n even but fails with n odd. You need to assign the return values, then it should all be find, i.e.,

x, x_work = iterate_f!(x,x_work,1);

Ok, that “works,” but the behavior is counter to my expectations.

Why?