const challenge

Janice Caron caron800 at googlemail.com
Fri Feb 1 22:29:10 PST 2008


On 2/1/08, Sergey Gromov <snake.scaly at gmail.com> wrote:
> On second thoughts, why would you want a function with a unique
> parameter ?  Nothing casts to unique(), so that the caller is always
> required to dup() or whatever.

So that you can do

    string s;
    string t = f( g( h( i( j( k( s ))))));

The functions f,g,h,i,j and k all return unique. The functions f,g,h,i
and j (but not k) all accept a unique parameter. In this example, no
duping or casting is required, because the temporary value is unique
right the way through the chain.


> Why force the user do it if you can
> always dup inside the function if you wish ?

That would be five dups in the above example. The fact is, if don't
mind duping, we don't need unique /at all/. e.g.

    string s;
    char[] t;
    char[] u = "hello".dup ~ s.dup ~ t;

But if we're concerned to minimise allocations and duplications, then
you need functions that /accept/ uniques, as well as functions that
return them, for reasons demonstrated in the first example.


> I think it only complicates
> the function usage.

As with an other function in-contracts, yes. But misuse would be
compiler checkable, so

    string s;
    string t = f( s );

(where f is as above) would be a compile error (cannot implicitly cast
invariant(char)[] to unique(char)[]). The caller of f would have to
change it to one of:

    string t = f( s.dup );
or
    string t = f( cast(unique)s );

In the latter case, of course, it would be the caller's responsibility
to guarantee uniqueness. If the programmer is wrong, undefined
behaviour results.



More information about the Digitalmars-d mailing list