How do you use templates in D?

Andrew Pennebaker andrew.pennebaker at gmail.com
Tue Oct 18 12:06:21 PDT 2011


I'm writing a D port of
QuickCheck<http://www.yellosoft.us/articles/2011/10/13/port-all-the-quickchecks>,
a unit test framework that works by testing properties. A property is a
function that accepts input values and returns a boolean, e.g. isEven(int
i).

The QuickCheck API's most important function is forAll, which should accept
a property and a collection of generators. E.g., isEven takes a single
integer, so the generators required are { genInt }. (I don't know the syntax
for a collection of differently-typed functions.)

The call would look like:

forAll(isEven, { genInt });

And the output would be something like:

*** Failed!
57

Because 57, a random number returned by genInt(), when passed to isEven(),
results in false.

Writing our own generator, we can test whether all even integers are indeed
even.

int genEven() {
   int i = genInt();

   if (i % 2 != 0) {
      i++;
   }

   return i;
}

forAll(isEven, { genEven });

Sample output:

+++ OK, passed 100 tests.

Recap:

forAll() accepts a property of type bool function(void), and a collection of
generator functions, of types *arbitrary_type* function(void). forAll calls
the generator functions, storing the values in another collection, and
passing the values to the property. If the property returns false, the
values are printed to the screen.

For a working C version of forAll, see qc <https://github.com/mcandre/qc>.
It uses a nasty void* trick, but I'd prefer not to resort to hacks in D if
possible.

The D version will be called dashcheck<https://github.com/mcandre/dashcheck>
.

Cheers,

Andrew Pennebaker
www.yellosoft.us

On Tue, Oct 18, 2011 at 2:55 PM, Graham Fawcett <fawcett at uwindsor.ca> wrote:

> On Tue, 18 Oct 2011 14:28:59 -0400, Andrew Pennebaker wrote:
>
>
> > Now I'm curious: How can I pass and accept a collection of lambdas? The
> > lambdas will each have different, arbitrary returns types. And how do I
> > call a function using a collection of values, something like Lisp's
> > (apply f args) ?
>
> Can you give an example of how such a thing would be used? Collection of
> lambdas, I understand; but what would you expect the return type to be?
>
> Graham
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20111018/0855b709/attachment.html>


More information about the Digitalmars-d mailing list