static interface

Leandro Lucarella llucax at gmail.com
Mon Nov 16 09:25:13 PST 2009


Why not? ;)

I know you might want to hit me for bringing just another feature request
inspired in Google's Go, but please do read it without preconceptions,
because I think the features I'm suggesting are mostly already in D, but
in a less convenient way.

With ranges, D is already using some kind of duck-typing. It's implemented
with template, template constraints and __traits(compiles)/is(typeof())
mostly. The range module makes extensive use of this trick.

All those features are great, and general and useful for a lot of things
besides duck-typing. But (compile-time) duck-typing is a very nice feature
which might deserve a little magic to avoid the boilerplate (or at least
odd implementation).

What I'm suggesting is just some syntax sugar for compile-time
duck-typing. My suggestion is to make this (a real example from the range
module):

static interface InputRange(T) {
	bool empty();
	T front();
	void popFront();
}

size_t walkLength(InputRange range, size_t upTo = size_t.max)
{
	// implementation
}

struct Stride(T): InputRange(T) {
	// implementation
}


Be somehow equivalent to:

template isInputRange(R)
{
    enum bool isInputRange = is(typeof(
    {
        R r;
        if (r.empty) {}
        r.popFront;
        auto h = r.front;
    }()));
}

size_t walkLength(Range)(Range range, size_t upTo = size_t.max)
if (isInputRange!(Range))
{
	// implementation
}

struct Stride(T) if (isInputRange!(Range)) {
	// implementation
}


The former syntax is much pleasant for both defining 'static interfaces'
and writing algorithms for them.

I didn't thought about this too much, and I'm sure there are plenty of
holes to be worked out, but I wanted to throw the idea out there to see
what people think about it.

What do you think?

-- 
Leandro Lucarella (AKA luca)                     http://llucax.com.ar/
----------------------------------------------------------------------
GPG Key: 5F5A8D05 (F8CD F9A7 BF00 5431 4145  104C 949E BFB6 5F5A 8D05)
----------------------------------------------------------------------
I always get the feeling that when lesbians look at me, they're thinking,
'*That's* why I'm not a heterosexual.'
	-- George Constanza



More information about the Digitalmars-d mailing list