Transients or scoped immutability

bearophile bearophileHUGS at lycos.com
Fri Apr 22 14:23:57 PDT 2011


This post contains uncooked ideas.

I'd like to create data structures:
- That once created are immutable, so there is no risk to write on them, etc;
- On the stack too, avoiding slower heap allocations and avoiding copying them from the mutable to the immutable version;
- Avoiding to keep in the function name space a dead name of the mutable version of the data structure;
- Avoiding calls to functions that may contain loops that DMD doesn't inline;
- Avoiding too much complex code for the programmer.

A syntax idea, a do{}transient(name1, name2, ...);:


void foo(char[] data) {
    do {
        int[256] count;
        foreach (char c; data)
            count[c]++;
        int x = ...
        auto bar = map!(...)(...x...);
    } transient(const count, const bar);
    // Here x is not visible.
    // Here count and bar are visible but read-only.
}
void main() {
    foo("this is a string");
}


A different syntax, that inverts the precedent idea and uses a sub-scope (it's a bit like a with(){}, but its purpose is not to access fields of a struct):


void foo(char[] data) {
    int[256] count;
    foreach (char c; data)
        count[c]++;
    int x = ...
    auto bar = map!(...)(...x...);
    // Here x, count, data and bar are visible and mutable.
    scope (const count, const bar, data) {
        // Here x is not visible.
        // Here count and bar are visible but read-only.
        // Here data is visible and mutable
    }
    // Here x, count, data and bar are visible and mutable.
}
void main() {
    foo("this is a string");
}


I think the first idea is a bit less bug-prone, and it avoids too much indenting of the code. Probably there are ways to invent a better syntax.

They have added the idea of "transients" is Clojure too:
http://clojure.org/transients?responseToken=07a82a51e4651b10f3a8ee4be09fe1f9f

This idea is good and it will help, but it needs a function call:
http://d.puremagic.com/issues/show_bug.cgi?id=5081

Bye,
bearophile


More information about the Digitalmars-d mailing list