www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Sorting array with different order

reply "Grzeogorz =?UTF-8?B?xYF1c3pjemVrIg==?= <grzegorz piklus.pl> writes:
I'm writing small web server to serve data as JSON. This data 
could be sorted based on various parameters (order and field to 
sort).

In this example I will use only 2 classes (but I need serve 10-20 
classes and each class have 5-10 attributes):

class Port {
   int number;
   Host[] host;
}

class Host {
   string macAddress;
   string ipAddress;
}

I have idea to use this struct:

struct Sort {
   string order = "desc"; // Sort order - DESC/ASC
   string sort_by;        // Filed to sort by
}

To create an associative array with sort function:

static this(){
   portSortMethods[ Sort( "desc", "number" ) ] = &sort!( "a.number 
 b.number", SwapStrategy.unstable, Port[] );

< b.number", SwapStrategy.unstable, Port[] ); hostSortMethods[ Sort( "desc", "macAddress" ) ] = &sort!( "a.macAddress > b.macAddress", SwapStrategy.unstable, Host[] ); hostSortMethods[ Sort( "asc", "macAddress" ) ] = &sort!( "a.macAddress < b.macAddress", SwapStrategy.unstable, Host[] ); hostSortMethods[ Sort( "desc", "ipAddress" ) ] = &sort!( "a.ipAddress > b.ipAddress", SwapStrategy.unstable, Host[] ); hostSortMethods[ Sort( "asc", "ipAddress" ) ] = &sort!( "a.ipAddress < b.ipAddress", SwapStrategy.unstable, Host[] ); } And write function like this for Hosts: Hosts[] sortHosts( Host[] collection, string order, string by ) { auto sortMethod = hostsSortMethods[ Sort( "desc", "macAddress ) ]; return sortMethod( collection ).release(); } But I have problem with type of portSortMethod and hostSortMethod. I will be glad if someone could help me with my problem.
Aug 07 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
Grzeogorz Ɓuszczek:

 I will be glad if someone could help me with my problem.

Such questions are better asked in D.learn newsgroup. Every time you instantiate the sort function with different template arguments, you generate a different type. So you could use a variant, or probably better to find a different solution. You could store just the arguments of the sort template, like the string "a.ipAddress < b.ipAddress" or the equivalent lambda, and later use it as arguments to instantiate the sort when you need it. Bye, bearophile
Aug 07 2013