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

"Nordlöw" via Digitalmars-d digitalmars-d at puremagic.com
Wed Nov 5 15:40:22 PST 2014


On Wednesday, 5 November 2014 at 16:54:38 UTC, Marc Schütz wrote:
> 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)));

Works! Thanks!

One thing: I tried to add support for integer based member 
indexing via tupleof at

https://github.com/nordlow/justd/blob/master/sort_ex.d#L21

but it errors as

sort_ex.d(42,46): Error: function expected before (), not 0 of 
type int
sort_ex.d(43,46): Error: function expected before (), not 0 of 
type int
sort_ex.d(42,6):        instantiated from here: sort!((a, b) => 
extractorFun!extractor(a) < extractorFun!extractor(b), 
cast(SwapStrategy)0, X[])
sort_ex.d(80,6):        instantiated from here: sortBy!(0, X[])
/home/per/opt/x86_64-unknown-linux-gnu/dmd/linux/bin64/src/phobos/std/algorithm.d(10266,9): 
Error: static assert  "Invalid predicate passed to sort: 
__lambda2"
sort_ex.d(42,6):        instantiated from here: sort!((a, b) => 
extractorFun!extractor(a) < extractorFun!extractor(b), 
cast(SwapStrategy)0, X[])
sort_ex.d(80,6):        instantiated from here: sortBy!(0, X[])

when I uncomment the last three tests. What's wrong?


More information about the Digitalmars-d mailing list