Chars sorting and copies

bearophile bearophileHUGS at lycos.com
Sat Oct 22 20:01:17 PDT 2011


Thanks for all the answers.

Steven Schveighoffer:

> a ~ b should technically be assignable to char[], since it's alread new  
> memory.  We may yet get there with pure functions being able to implicit  
> cast to immutable.

Isn't that kind of the opposite?
Is this already in Bugzilla?

Some versions I have written, there is no very good solution, it seems:


import std.algorithm, std.exception;

void main() {
    string a = "red";
    string b = "green";
    int[string] aa;

    // Works in D1.
    // aa[(a ~ b).sort] = 1;

    // Works in D2, but will stop working.
    aa[(a.dup ~ b.dup).sort.idup] = 1;

    // Works in D2, but will stop working.
    char[] ab = (a.dup ~ b.dup).sort;
    aa[assumeUnique(ab)] = 2;

    // If keys don't actually need to be strings
    // the code gets a bit simpler.
    int[immutable(ubyte[])] aa2;

    // not good
    // aa2[assumeUnique(sort(cast(ubyte[])(a ~ b)))] = 3;

    // not good?
    // aa2[assumeUnique(sort(cast(ubyte[])(a ~ b)).release())] = 3;

    // just 1 copy, two visible casts, 3 lines
    auto ab4 = cast(ubyte[])(a ~ b);
    ab4.sort();
    aa2[cast(immutable(ubyte[]))ab4] = 3;

    // a visible cast and an hidden cast
    ubyte[] ab2 = cast(ubyte[])(a ~ b);
    ab2.sort();
    aa2[assumeUnique(ab2)] = 3;

    // 2 lines, more complex looking
    auto ab3 = sort(cast(ubyte[])(a ~ b)).release();
    aa2[assumeUnique(ab3)] = 3;
}


Bye,
bearophile


More information about the Digitalmars-d-learn mailing list