equivariant functions

Denis Koroskin 2korden at gmail.com
Sun Oct 12 14:09:07 PDT 2008


On Sun, 12 Oct 2008 23:34:05 +0400, Andrei Alexandrescu  
<SeeWebsiteForEmail at erdani.org> wrote:

> 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);
>
> [snip]
>
> There's been several proposals in this group on tackling that problem.
>
> [snip]
>
> I discussed with Walter a variant that implements equivariant functions  
> without actually adding an explicit feature to the language. Consider:
>
> typeof(s) stripl(const(char)[] s);
>
> This signature states that it returns the same type as an argument. I  
> propose that that pattern means stripl can accept _any_ subtype of  
> const(char)[] and return that exact type. Inside the function, however,  
> the type of s is the type declared, thus restricting its use.
>

Sounds more like an easter egg to me.
But that will not work, I'm afraid. Consider the following example:

char* strstr(char* str1, const(char)* str2)
{
     return str1; // it's buggy, but who cares?
}

char* s = "hello".dup.ptr;
char* p = strstr(s, "o");
p[0] = 0;

printf("%s", s); // prints 'hell'

Let's turn it into 'equivariant function':
const(char)* strstr(const(char)* str1, const(char)* str2);

Do you see the problem already?

const(char)* strstr(const(char)* str1, const(char)* str2)
{
     // which one of the two arguments is of dynamic constancy? Both?
     return str2; // <g>
}

char* s = "hello".dup.ptr;
char* p = strstr(s, "o");
p[0] = 0; // bang! access violation


The dynamic constancy attribute should be distiguishable from other  
attributes like const/invariant.

May I suggest one of my personal preference? Here it is:

sameconst(char)* strstr(sameconst(char)* str1, const(char)* str2)
{
     return str2; // compile-time error. Can't cast const(char)* to  
sameconst(char)* implicitly
}



More information about the Digitalmars-d mailing list