On Thursday, October 20, 2011 21:49:27 bearophile wrote:
> I have many strings and I want to use as associative array kay a sorted
> concat of two strings (it's a signature of the two strings):
> 
> 
> import std.algorithm;
> void main() {
>     string a = "red";
>     string b = "green";
>     int[string] aa;
>     //aa[(a ~ b).sort] = 1;
>     //aa[(a ~ b).sort.idup] = 1;
>     aa[(a.dup ~ b.dup).sort.idup] = 1;
> }
> 
> I think the first way used to work, the second way was recently forbidden
> (and you can't use char[] as associative array key). The third way now
> works, but array.sort will go away.
> 
> So do you know what's a copy-minimizing (and possibly short) way to perform
> this, in future?

The elements in a string are immutable. I don't see how the first twe sorts 
_ever_ worked, unless it was a bug. The reality of the matter is that if you 
want to sort an array, its elements must be mutable, but if you want to use it 
as a key in an AA, its elements must be immutable. So, you're either going to 
have to copy them or cast to immutable.

Also, you're going to have to use std.algorithm.sort eventually, and isn't 
going to work on chars or wchars (and what you're doing now is buggy unless 
you're restricting yourself to ASCII). So, you're either going to have to do 
one of

1. Use dchar[] to sort and then convert it to dstring for the key (either by 
casting or copying).

2. Use dchar[] to sort and then convert it to a string for the key (which 
results in a copy).

3. If you're using ASCII only, you could use char[], cast it to ubyte[] to 
sort it, and then cast it to string to use as the key (or idup it).

But sorting and and immutability are obviously at odds with one another, 
requiring either a copy or a cast, and sorting really isn't going to work with 
char[] or wchar[], unless you restrict yourself to values that fit in a UTF-8 
or UTF-16 code unit.

- Jonathan M Davis

Reply via email to