sortOn: sorts range of aggregates by member name(s)

via Digitalmars-d digitalmars-d at puremagic.com
Wed Nov 5 08:54:36 PST 2014


On Wednesday, 5 November 2014 at 16:07:40 UTC, Nordlöw wrote:
> On Wednesday, 5 November 2014 at 14:36:11 UTC, Marc Schütz 
> wrote:
>> It's intuitive and concise. Plus, Ruby uses `sort` and 
>> `sort_by` for the same functionality, exactly in parallel, so 
>> it will be familiar to many users.
>
> Here's my first working but primitive version.
>
> https://github.com/nordlow/justd/blob/master/sort_ex.d#L15
>
> How do I extend it to support
>
> - variadic number of extractors
> - sortBy("x")

My idea was something along these lines (untested):

     template extractorFun(alias extractor) {
         static if(is(typeof(extractor) : string)) {
             auto ref extractorFun(T)(auto ref T a) {
                 mixin("with(a) { return " ~ extractor ~ "; }");
             }
         } else {
             alias extractorFun = extractor;
         }
     }

     alias fn = extractorFun!extractor;
     r.sort!((a, b) => (fn(a) < fn(b)));


More information about the Digitalmars-d mailing list