Chars sorting and copies
Steven Schveighoffer
schveiguy at yahoo.com
Mon Oct 24 08:41:33 PDT 2011
On Sat, 22 Oct 2011 23:01:17 -0400, bearophile <bearophileHUGS at lycos.com>
wrote:
> 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?
No, if a ~ b would call a pure function that returns mutable when
possible, then you could use it for mutable, immutable, or const.
> Is this already in Bugzilla?
Somewhat, although I like using the pure function avenue to ensure
immutable does not violate const than the crazy rules we came up with here:
http://d.puremagic.com/issues/show_bug.cgi?id=1654
Note this was in the infancy of my D knowledge ;)
> 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;
> }
I honestly am not sure your specific problem is solvable without a lot of
special cases. It may be you have to write a sub-function that hides the
mess.
-Steve
More information about the Digitalmars-d-learn
mailing list