Phobos2: sorting and std.typecons.Tuple
bearophile
bearophileHUGS at lycos.com
Mon Apr 27 08:33:03 PDT 2009
This is code I have had to write:
auto arr = genArray();
schwartzSort!("...")(arr);
return result;
Often you know your array is small (or you don't want to sort the original array/range), so you can add a functional-style variant that sorts a copy, 33% of the code lines, a big saving of code:
return schwartzSorted!("...")(genArray());
---------------
schwartzSorted isn't a nice name, maybe you can find something shorter can simpler to write, like "keySort" (key is the mapping function).
---------------
The toString of one Tuple gives me:
Tuple!(immutable(char)[],float)(hi, 1)
But I think that's a bit overkill and very long, in most situations you know the type, so something like the following is better and much less noisy (especially if you have to print an array of them (also notice the useful "" around the string):
tuple("hi", 1)
I have seen than D2 writeln() prints [] around associative arrays, but not around arrays, while D1 prints [] around both of them. This is a regression even compared to the raw behavior of D1.
---------------
Tuple misses opCmp and toHash. I don't want to post pages of code here, but I suggest you to take a look at:
- Record() struct in module templates
- hash() function template in module func
- structCmp() function template in module func
The code is here still:
http://www.fantascienza.net/leonardo/so/libs_d.zip
If you have questions about that please ask.
This allows people to use Tuples as keys of AA/sets and to sort them, even if they recursively contain other Tuples (or even if they contain normal structs). This allows to use Tuple in a *much* more flexible way in programs, increasing their usefulness three-fold.
Bye,
bearophile
More information about the Digitalmars-d
mailing list