DK.
DK.

Reputation: 59005

D Templates: Sort a list of types

Assume you have a type like the following:

struct Value(int v_)
{
  static const v = v_:
}

How would you sort a list of these types, assuming an interface something like this:

alias Sorted!(Value!(4), Value!(2), Value!(1), Value!(3)) SortedValues;

You may use D 2.x features if it makes for a better solution, but please state if you do so.

I'll post my solution in a day or so. :)

Upvotes: 4

Views: 204

Answers (3)

DK.
DK.

Reputation: 59005

Here's my solution. Note quite as cool as FeepingCreature's, but probably simpler to understand; it works by recursively inserting the first type into the rest of the list (after having sorting it).

module sort;

/*
 * Tango users substitute "tango.core.Tuple" for "std.typetuple" and "Tuple"
 * for "TypeTuple".
 */

import std.typetuple;

struct Val(string v_)
{
    static const v = v_;
}

template Sorted_impl(T)
{
    alias TypeTuple!(T) Sorted_impl;
}

template Sorted_impl(T, U, V...){

    static if( T.v < U.v )
        alias TypeTuple!(T, U, V) Sorted_impl;

    else
        alias TypeTuple!(U, Sorted_impl!(T, V)) Sorted_impl;
}

template Sorted(T)
{
    alias TypeTuple!(T) Sorted;
}

template Sorted(T, U...)
{
    alias Sorted_impl!(T, Sorted_impl!(U)) Sorted;
}

pragma(msg, Sorted!(Val!("a")).stringof);

pragma(msg, Sorted!(Val!("b"), Val!("a")).stringof);

pragma(msg, Sorted!(
    Val!("d"), Val!("a"), Val!("b"), Val!("c")
).stringof);

static assert( false, "nothing to compile here, move along..." );

Upvotes: -1

BCS
BCS

Reputation: 78545

By the way unless you have other reasons to do it there is no need to wrap the value in structs as tuples work just fine with values as well.

alias Sorted!(4, 2, 1, 3) SortedValues;

Upvotes: 1

FeepingCreature
FeepingCreature

Reputation: 3778

Using D 1.0, have a QuickSort!

http://paste.dprogramming.com/dplgp5ic

Upvotes: 3

Related Questions