A const idiom + a different 'delete'

bearophile bearophileHUGS at lycos.com
Wed Aug 11 08:59:29 PDT 2010


This is an little idiom that is getting common in my code, it's similar to the 'transients' of Clojure language.

Often I have to build a simple data structure like an array associative or another kind of array, it needs to be mutable because I fill it in few lines of code code. When it's complete I never need to change it again, so now I'd like it to be const. I can't freeze it, so I have to create a new variable:


void main() {
    int[int] aa_;
    foreach (i; 0 .. 10)
        aa_[i] = i * i;

    // now I'd like to freeze aa
    const(int[int]) aa = aa_;
}


If the array is fixed-sized the situation is worse because the last line copies the whole array.

Sometimes I use a small function to do this.

This is an alternative way to write it that I've never used because I don't like it much:

void main() {
    const(int[int]) aa = {
        int[int] result;
        foreach (i; 0 .. 10)
            result[i] = i * i;
        return result;
    }();
}


In Python I sometimes use "delete" to remove a name from the local namespace that I don't want to use any more. This cleaning purpose may be a replacement purpose for the delete keyword, but I don't know if you like it:


void main() {
    int[int] aa_;
    foreach (i; 0 .. 10)
        aa_[i] = i * i;

    // now I'd like to freeze aa
    const(int[int]) aa = aa_;
    delete aa_; // from now on the 'aa_' name can't be seen/used.
}


Here delete doesn't clean the aa_, it just removes the aa_ name from the local namespace. If there's another reference to aa_ it is unchanged and it sees an unchanged associative array. The point of removing the aa_ name is to keep the namespace tidy.

As with variable definitions a goto can't jump over one delete. In Python you can later create a new variable with the same name, but in D the variable doesn't actually vanish from the stack, so I think it's better to disallow successive redefinitions of it.

Bye,
bearophile


More information about the Digitalmars-d mailing list