Extended Type Design: further examples

Andrei Alexandrescu (See Website For Email) SeeWebsiteForEmail at erdani.org
Mon Mar 19 15:05:29 PDT 2007


(Reposted after cleanup :o))

kris wrote:
> How about some further example? Given these sigs:
> 
> struct Foo
> {
>    int a;
> }
> 
> class Bar
> {
>    char[] b;
> }
> 
> void fooish (inout Foo foo) {}
> 
> char[] barish (Bar bar) {return bar.b;}
> 
> 
> 1) how do I modify the function decls to have the compiler *enforce* 
> readonly upon the referenced content? e.g. Foo.a and Bar.b cannot be 
> mutated within the function body?

void fooish (const ref Foo foo) {}

char[] barish (const Bar bar) {return bar.b;}

> 2) how does the fooish() decl change to have the compiler *enforce* a 
> readonly-view of the returned bar.b?

const char[] barish (const Bar bar) {return bar.b;}

> 3) where fooish() has a Foo* rather than an inout Foo, is there any 
> change to the modified decl vis-a-vis #1?

void fooish (const Foo* foo) {}

By the way, a couple of days ago I've had an idea. Many people here ask
for a "string" alias because char[] is a tad hard to type and uneasy on
the eyes. Probably a good candidate would be:

alias invariant char[] string;

The resulting type is pretty damn slick:

1. You can alias it and slice it til you get blue in the face - no
confusion ever, because nobody can overwrite the contents underneath
your alias.

2. The EnsureCString(ref string) function will reallocate and copy the
string at most once and only for a slice, never for the "original"
string which was zero-terminated during construction.

3. The ~= operator works (somewhat surprisingly).

4. It's very, very rare that you want to modify some random character in
a string, and when you do, use a char[] and then copy it back into a
string, or rebuild the string from slices!

5. The Java experience (where String is immutable and StringBuffer is
the mutable, build-me-piecemeal object) turned out to be largely
successful, modulo syntax details that are not so elegant.

6. It meshes great with literals, which are exactly invariant arrays of
characters:

string hi = "Hello!"; // no dup needed! And it's 100% safe!

So it looks like we have solved the string issue in an unexpectedly
elegant way - by simply combining two features: invariant and array.


Andrei




More information about the Digitalmars-d mailing list