If you're willing to tolerate some performance hit, a simple wrapper
type COWArray{T,N}
A::Array{T,N}
copied::Bool
end
and then defining variants of setindex! that look like
function setindex!(A::COWArray, v, indexes...)
if !A.copied
A.A = copy(A.A)
A.copied = true
end
setindex!(A.A, v, indexes...)
end
should do the trick quite easily.
--Tim
On Saturday, September 27, 2014 08:47:06 PM John Myles White wrote:
> Matlab’s semantics are called copy-on-write. I suspect you couldn’t
> implement those semantics without several months of work on a new Array
> type.
>
> — John
>
> On Sep 27, 2014, at 1:52 PM, Stephan Buchert <[email protected]> wrote:
> > Thanks for the kind explanations and references that I had missed, seems
> > clear to me now.
> >
> > As a footnote, I was looking for a way to enforce Matlab-like behaviour,
> > that is changing the contents of an array argument inside a function is
> > invisible to the caller.
> >
> > Unsuccessful attempt:
> >
> > function f!(x)
> > x=x # <== does not copy x, it seems to get optimized away
> > x[:]=x+1 # <== this is still visible to the caller
> > end
> >
> > but
> >
> > function f(x)
> > x=copy(x) # <== copies x in function scope, for numeric arrays x=x+0
> > works also x{:]=x+1 # <== this is now invisible to the caller
> > end