digitalmars.D - using unaryFun in functions that take a comparator (eg sort etc):
- Timothee Cour (30/30) May 28 2013 very often I would wish that sort (+ related functions) could take unary...
- David Nadlinger (4/7) May 28 2013 In this case, schwartzSort might actually be more appropriate.
- Andrei Alexandrescu (6/15) May 28 2013 I actually have a branch in my code that does exactly that. I abandoned
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.
May 28 2013
On Tuesday, 28 May 2013 at 08:16:47 UTC, Timothee Cour wrote:sort!"foo(a)" <=>sort!(unaryToBinaryComp!(unaryFun!"foo(a)")) <=> sort!"foo(a) < foo(a)" sorting in reverse order is easy: just use sort!"-foo(a)"In this case, schwartzSort might actually be more appropriate. But in general, I see your point. David
May 28 2013
On 5/28/13 4:16 AM, Timothee Cour wrote: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); } }I actually have a branch in my code that does exactly that. I abandoned it because the code, error messages, and documentation got really confusing. It may be worth to add a keySort algorithm that only works with unary keys, but then I thought people can always write a small lambda. Andrei
May 28 2013