[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: MATLAB



Michael Vanier <mvanier@bbb.caltech.edu> writes:

>> From: Morgan McGuire <morgan3d@yahoo.com>
>> 
>> > Copy-on-mutate?  What's that?
>> 
>> Copy-on-mutate is a form of lazy evaluation.  It means that:
>> 
>> A = B
>> 
>> doesn't actually copy the values from B into A (A and B are values, not
>> pointers), instead it just remembers that A is supposed to be equal to
>> B.  This saves memory and time.  If we later mutate A or B, the copy
>> occurs.  If you're extra slick, you can put off the copy until a
>> significant mutation occurs (just accumulate the mutations to apply
>> later) or until someone actually needs the value.
>
> In python, this is the difference between:
>
>   a = b[:]  # copy the entire array b into a
>
> and
>
>   a = b     # a now refers to the same array as b
>
> Seems pretty straightforward, unless I'm missing something deeper.

Yes, you're missing something deeper.

You got the Python examples correct, but neither of them results in
copy-on-mutate.  Since Morgan's direct explanation didn't do it, I'll
try an example in pseudo-Python.  This wouldn't really make too much
sense given the name/assignment model in Python, but I'll use the
syntax for the sake of sticking with your examples.

Take a hypothetical operator in Python to perform the copy-on-mutate
style of assignment, and call it "<-".

>>> a = function_returning_large_list()
>>> b <- a

At this point there is only one copy of the list in question, and
evaluating either a or b will provide the data from exactly the same object.

>>> b.append(4)

Here is where the magic happens.  When you take an action that mutates
b (but not before then) a copy is made which is then mutated.  b now
refers to that mutated copy.  a continues to point to the same list
that it was originally assigned.

(Note that the above statement and paragraph are also true if you
transpose "a" and "b".)

Neither of the two Python assignments that you quoted performs in this
fashion.  Python does not support this model in any general way.

Copy-on-mutate gives you the effect of your first example, but in many
cases may also provide close to the resource-efficiency of the second.

-Justin