Mutating closure?

I am trying to define a closure which mutates its argument, without luck. Is there a way to define a closure which is mutating? Here’s an example of what I’m trying to achieve:
Thanks!

function a!(x)
    for i = 1:size(x,1)
        x[i] = 2.0 * x[i]
    end
    y = 1.0
    return x
end

function a!(x,y)
    for i = 1:size(x,1)
        x[i] = 2.0 * x[i]
    end
    y = [1.0]
    return x
end


function main()
    x = [1.0]
    y = [1.0]
    # one argument
    println("one argument")
    println("x before function", x)
    a!(x)
    println("x after function", x)
    f! = x -> a!(x)
    println("x before closure", x)
    f!(x)
    println("x after closure", x)
    # two arguments
    println("two arguments")
    println("x before function", x)
    a!(x,y)
    println("x after function", x)
    g! = x -> a!(x,y)  #### THIS IS WHAT DOES NOT WORK.
    println("x before closure", x)
    g!(x,y)
    println("x after closure", x)
end

main()


It allocates new object in the second method, you probably want:
y[1] = 1.0

Also later invocation of g! seems to be not correct. If y is catched into a closure, you should pass only g!(x)

1 Like

Thanks! A silly mistake on my part. Now it’s working as I hoped it would.

1 Like