using unaryFun in functions that take a comparator (eg sort etc): sort!"a[0]" <=> sort!"a[0]<b[0]"
Timothee Cour
thelastmammoth at gmail.com
Tue May 28 01:16:38 PDT 2013
very often I would wish that sort (+ related functions) could take unaryFun
arguments and convert them to binaryFun as follows:
//pseudocode:
template unaryToBinaryComp(alias foo) {
bool unaryToBinaryComp(T)(T a, T b) if (__traits(compiles,foo(a) < foo(b))
) {
return foo(a) < foo(b);
}
}
Using this we could support much nicer syntax for sorting with unary
functions, for example:
sort!"foo(a)" <=>sort!(unaryToBinaryComp!(unaryFun!"foo(a)"))
<=> sort!"foo(a) < foo(a)"
sorting in reverse order is easy: just use sort!"-foo(a)" (works for
signed, unsigned, floating point types etc).
Examples of use:
E1)
struct A{
double score;
int index;
}
[A.init,A.init].sort!"a.score";
instead of:
[A.init,A.init].sort!"a.score < b.score";
E2)
mytuple.sort!"a[0]"
instead of:
[A.init,A.init].sort!"a[0]<b[0]"
I find that in large majority of cases, binary fun is used in that way. So
let's support both unaryFun and binaryFun.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20130528/93627f3d/attachment.html>
More information about the Digitalmars-d
mailing list