I want to pass a mutable object or array into a function and be sure that the object won’t be changed by that function. Is there an immutable wrapper I can use like
I know there are conventions like
f!(x) but I would like a bit more assurance.
I do believe that, in general, no. Because every function that works over the type would need to have a method for the wrapper too, and at the same type this wrapper would need to be able to distinguish between things that change the object or not.
The only way I see is that: all your functions do not specify the type of the object they work with. Then you use a wrapper type that defines a
Base.getproperty that delegates the query to the wrapped object. However, this will not prevent you changing an object that is stored in a field of the object (for example, if you have a vector field).
I don’t think there’s a way to guarantee that a mutable object is not modified. Julia does not have a notion of private fields, so it is always possible to manipulate the fields directly. A partial solution would be to introduce a wrapper type which errors if any of the usual modifiers like
setproperty! are called, but as @Henrique_Becker pointed out this wrapper would likely have to be specific to the type of object that you are working with (e.g.
AbstractArray). So all in all, I’d say it’s not worth the fuss.
To complement, what you want is something that Ruby has done well. Every object automatically has a
freeze! method, and if you call it, any change to a field of the object incurs in error.