Feature request: variant of -> that uses current bindings

It is a documented feature of Julia (see Performance Tips · The Julia Language) that using a variable from the main body of a function in an inner function causes the inner and outer copy of the variable to be bound together. Although this provides the programmer with additional flexibility in some situations, it is often not needed and causes a performance loss. As mentioned in the manual, if the inner function needs only the current binding of the outer variable, then the programmer indicates this with let statements. I would like to request a variant of ->, say -->, that automatically uses current bindings of all outer variables and thus frees the programmer from writing many let statements.

E.g., in the following code, I’d like to be able to write fn2 = x --> q*x with the same effect as the actual definition of fn2 below.

function testbindings()
    p = 8
    fn = x -> x*p
    println(fn(2))
    p = 5
    println(fn(2))
    q = 5
    fn2 = let q = q
        x -> q * x
    end
    println(fn2(2))
    q = 10
    println(fn2(2))
    nothing
end

which yields output 16, 10, 10, 10

1 Like

There’s GitHub - c42f/FastClosures.jl: Faster closure variable capture which does this (with a different syntax)

I agree that FastClosures.jl does what I requested. However, the source code for FastClosures.jl has many comments expressing reservations that the code may not always work, etc., because it tries to simulate the compiler as it macro-expands without actually invoking the compiler. Therefore, it would be better if this functionality could be built into the compiler itself.