Lazy evaluation: overloading the assignment operator?

Charles Sanders C.delete_this.Sanders at BoM.GOv.AU
Thu May 3 00:22:02 EDT 2007


Diez B. Roggisch wrote:
> I fail to see where laziness has anything to do with this.
 > In C++, this problem can be remedied with the so called
 > temporary base class idiom.

	I have seen this referred to as lazy evaluation in C++,
so I suspect that Diez and Sturia are using "Lazy evaluation"
in different contexts with different meaning.

> But this has nothing to do with laziness, which does not
 > reduce the amount of code to execute, but instead defers the
 > point of execution of that code.

	But that is precisely what Sturia is suggesting, defer
(for a few nanoseconds) the evaluation of the multiplications
and addition until the assignment occurs. Admittedly a big
difference to the lazy evaluation implied by python's yield
statement, but still a version of lazy evaluation and (at
least sometimes) referred to as such in a C++ context.

	I am a python newbie (about one month) but I think
some of what Sturia wants could be achieved by partially
following what is usually done in C++ to achieve what he
wants. It would involve a replacement array class (possibly
derived from NumPy's arrays) and a proxy class.

	+ Addition, multiplication, etc of arrays and proxy
	  arrays does not return the result array, but returns
	  a proxy which stores the arguments and the
	  operation.

	+ Array indexing of the proxy objects results in
	  the indexing methods of the arguments being
	  called and the operation being carried out and
	  returned. In C++ this is normally very efficient
	  as the operations are all defined inline and
	  expanded by the compiler.

	+ If necessary, define an additional method to evaluate
	  the entire array and return it.

I think this would allow code like (if the new array type is
XArray)

	a = Xarray(...)
	b = Xarray(...)
	c = Xarray(...)
	d = Xarray(...)

	y = a*b+c*d   # Returns a proxy object

	x = y[4]      # Computes x = a[4]*b[4] + c[4]*d[4]

	v = y.eval()  # Evaluates all elements, returning Xarray

	z = ((a+b)*(c+d)).eval()  # Also evaluates all elements

Whether it would be any faster is doubtful, but it would eliminate
the temporaries.

Charles



More information about the Python-list mailing list