Copy a function

Let’s say I want to store a function in a struct.To do this, I pass this function to the constructor of the structure. However, if at some point later I redefine the original function, then the function inside the structure will also change, which is not desirable for me:

struct MyStruct{F}
    func :: F
end

foo(x) = 2*x

s = MyStruct(foo)

println(foo(2))   # 4
println(s.func(2))   # 4   desirable output 

foo(x) = 4*x

println(foo(2))   # 8
println(s.func(2))   # 8   undesirable output

Is there a way to copy the function foo so that the stored function func will not be affected by any subsequent redefinition of foo ? Unfortunately, copy and deepcopy do not work.

Standard functions are singleton, there is one and only one instance of them possible.
Use anonymous functions instead,

foo = x -> 2x
5 Likes

Thank you.