DSpec / Templates + Delegates

Jacob Carlborg doob at me.com
Tue Mar 30 11:57:58 PDT 2010


On 3/30/10 13:58, Ruun wrote:
> Hi everyone,
>
> for my coming projects i was searching for a BDD-Framework similar like
> Ruby/RSpec or Scala/ScalaTest.
> Unfortanetly, i didn't find either an implementation on dsource.org or
> something about here on the mailing list (Especially
> for D2).
>
> After looking into the old source of Tango-based DUnit, some postings
> here on the mailing list about assertions / unittests, i started a small
> try with Phobos D2 and i'm currently really amazed how clear the API can
> be by using templates + delegates + alias.
>
> If someone is interested, i recently hosted a project DSpec on
> dsource.org and provide an experimantel example there
> http://www.dsource.org/projects/dspec/
> (Current source can be also found)
>
> I'm not sure if something similar is possible in D1 and honestly it's
> the first time i'm currently working with Templates in D so intensely.
> But after seeing such possibilities, i'm so impressed about D2.
>
> void each(alias array, T : T[] = typeof(array))(void delegate(T item) dg) {
> foreach(T i; array)
> dg(i);
> }
>
> int[] array = [1, 2, 3, 4];
> int b = 10;
>
> each!(array) = (int item) {
> writefln("%d", item + b);
> };
>
> This is almost looking like an iteration in Ruby and Scala!
> (I hope i'm not abusing the alias parameter in templates)
>
> Chris

To make it look a little more like Ruby or Scala you change the each 
function to something like this, using some operator overload abuse:

struct EachHelper (T)
{
	T[] array;

	void opIn (void delegate (T item) dg)
	{
		foreach (i, array)
			dg(i);
	}
}

void each (T) (T[] array)
{
	return EachHelper!(T)(array);
}

Then use it like this:

int[] array = [1, 2, 3, 4];
int b = 10;

array.each in (int item) {
	writefln("%d", item + b);
};

The above code is the same as the following:

each(array).opIn((int item) {
	writefln("%d", item + b);
});

I think all the above code will work both in D1 and D2.



More information about the Digitalmars-d mailing list