Reconstruct closure?

I have some function like

adder(x) = y->x+y

which is said to lower to roughly

struct ##1{T}
    x::T
end

(_::##1)(y) = _.x + y

function adder(x)
    return ##1(x)
end

Now if I do

g = adder(3)
println(typeof(g))

the output will look kind of like:

var"#1#2"{Int64}

If only have g, and adder can be any arbitrary function that I don’t know, then Is there a way I can construct an adder with a different x? e.g. I tried

julia> typeof(g)(5)
ERROR: MethodError: no method matching var"#1#2"{Int64}(::Int64)
Stacktrace:
 [1] top-level scope
   @ REPL[39]:1

Probably easiest to use Accessors.jl (or Setfield.jl) for this:

julia> plus(x) = y -> x + y
plus (generic function with 1 method)

julia> p2 = plus(2)
#plus##0 (generic function with 1 method)

julia> using Accessors

julia> p3 = @set p2.x = 3
#plus##0 (generic function with 1 method)

julia> p2(1)
3

julia> p3(1)
4
3 Likes

amazing! thank you!