Range returning an array

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Tue Apr 9 13:03:01 PDT 2013


Hello all,

I have a situation in a program I'm writing where it's convenient to define a
range whose return value is an array.  Something like:

struct MySimulation(T)
{
	T[] var;
	T diff, convergence;

	auto front() @property
	{
		return var;
	}

	bool empty() @property
	{
		return (diff < convergence);
	}

	void popFront()
	{
		// update values in var
		// and calculate diff
	}
}

Now, the problem with a design like this is that it's unsafe, in the sense that,
let's say I do something like,

	T[] output;
	foreach(opvar; mySim)
		output = opvar;

... then, at the end of this loop, output will not be the same as it was set to
with the last assignment, because popFront() will have been called one last time
prior to the "empty" condition being set to true.

Now, there are a number of ways I can think of to avoid this.  One is to return
var.dup rather than var from front(), but this is undesirable because it will
hit performance in a big way.  Another might be to calculate the updated value
of var in a temporary array, and update var itself only if the diff is greater
than the convergence criterion.

However, I'm curious enough about this problem that I thought I'd throw it open
to everyone else to see if anyone has a better idea than one of these.  The
challenge here is to ensure really good performance while not risking bad or
incorrect results leaking outside of the range.

Any thoughts? :-)

Thanks & best wishes,

    -- Joe


More information about the Digitalmars-d-learn mailing list