equivariant functions

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon Oct 13 05:48:13 PDT 2008


Michel Fortin wrote:
> On 2008-10-12 15:34:05 -0400, Andrei Alexandrescu 
> <SeeWebsiteForEmail at erdani.org> said:
> 
>> Many functions return one of their parameters regardless of the way it 
>> was qualified.
>>
>> char[] stripl(char[] s);
>> const(char)[] stripl(const(char)[] s);
>> invariant(char)[] stripl(invariant(char)[] s);
>>
>> Stripl is not a particularly good example because it needs to work on 
>> wchar and dchar too, but let's ignore that aspect for now.
>>
>> There's been several proposals in this group on tackling that problem.
> 
> I'm not sure why one would one add another syntax feature for this. I 
> mean: we have templates which are capable of this. Sure, templates are 
> instanciated only when needed and that's not what we want, but I think 
> we'd better reuse the syntax we have, adding a modifier and if necessary 
> for forcing one instanciation at the definition site when possible.

That's a good point.

> I'm not sure if this is valid in D2 (I don't have a D2 compiler in front 
> of me right now), but let's say that this makes C any subtype of 
> const(char):
> 
>     C strip1(C : const(char))(C[] s);

High time to change fonts in your newsreader: it's stripL, not 
stripOne... :o) Here's a better way to write that template:

S stripl(S)(S s) if (is(S : const char[]));

meaning S is a subtype of const char[].

> This template does what you want, except that it's instanciated only at 
> the call site, making it unusable in some situations. What we need is to 
> make this specific template work like C# and Java's generics: only one 
> instanciation dealing with multiple parametrized types. So let's extend 
> the template syntax a little:
> 
>     C strip1(equivariant C : const(char))(C[] s);
> 
> Hum, what did that change? Well, the new "equivariant" keyword I added 
> imposes new restrictions to the template argument, such as you cannot 
> know the exact type beyond the type restriction in the parameter 
> definition.

I think this could work, but then if you take the hit of a new keyword, 
maybe Denis' solution works even better. It's less verbose and easier to 
understand.


Andrei



More information about the Digitalmars-d mailing list