Behaviors of `deepcopy` for a function constructed with different ways of referencing a global variable

Thanks for the hint!! It seems like the way I thought of Function, as struct with attributes (fields) and methods, is no longer applicable in this case. Here’s what I understand now:

For f1, box was not an assigned field of the closure it returns, but simply a variable directly inside the definition (function body) of the closure, except it’s declared outside the closure scope. So, as soon as f1 is defined, even before it is called, it is certain that there can only be one instance of the closure (which technically should not even be considered a “closure” based on your and @danielwe 's comments (1, 2) on the other post) that f1 generates. Thus, typeof(f1c) is deemed a singleton type. And because typeof(f1c) is a singleton, it should have one and only one instance (characterized by its type information), which is f1c. So deepcopy cannot just create another instance that is not identical to f1c. Therefore, deepcopy cannot sever the f1c’s reference to the global variable box either.

However, for f2, there can be many instances of the closure it generates, depending on the specific value of localBbox passed in. So f2 in fact behaves like a struct with a single field (store the value of localBbox for each instance) and a corresponding method that uses the field. Hence, f2c is not an instance of a singleton type. Correspondingly, deepcopy also copies the data stored inside it.

Hopefully, what I described above is a more accurate mind model of how closures and functions with out-of-scope variables generally work. Thanks!!

1 Like