Phobos2: sorting and std.typecons.Tuple

dsimcha dsimcha at yahoo.com
Mon Apr 27 09:01:45 PDT 2009


== Quote from bearophile (bearophileHUGS at lycos.com)'s article
> 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

Vote++ for giving Tuple a decent default implementation of opCmp and toHash.  Then
maybe I could use Tuple to represent joint samples from a probability distribution
(I often want to use hash tables to count the frequency of each observation using
hash tables).  Right now, I use a really ad-hoc struct to do this, and I'm sure
that my scheme for taking the hashes of the elements of the struct and turning
them into one hash is sub-optimal, but it works.

As far as opCmp, here's a useful snippet for a default opCmp for tuples.  It works
well when all you need is an arbitrary transitive ordering for use in a binary
tree or something.

int opCmp(const ref typeof(this) other) const {
    foreach(ti, elem; other.tupleof) {
        if(this.tupleof[ti] < elem) {
            return -1;
        } else if(this.tupleof[ti] > elem) {
            return 1;
        }
    }
    return 0;
}



More information about the Digitalmars-d mailing list