digitalmars.D.learn - Regarding topN and topNCopy
- bearophile (53/53) Jun 30 2012 Three related questions, about three possible Phobos little
Three related questions, about three possible Phobos little enhancement requests. This curious code compiles and sorts in reverse the arrays a and b according to the a,b pairs: import std.stdio, std.algorithm, std.range; void main() { auto a = [10, 20, 30]; auto b = ["c", "b", "a"]; writeln(a, " ", b); sort!q{a > b}(zip(a, b)); // OK writeln(a, " ", b); } Output: [10, 20, 30] ["c", "b", "a"] [30, 20, 10] ["a", "b", "c"] But this code doesn't compile: import std.stdio, std.algorithm, std.range; void main() { auto a = [10, 20, 30]; auto b = ["c", "b", "a"]; writeln(a, " ", b); topN!q{a > b}(zip(a, b), 4); // error writeln(a, " ", b); } With the latest DMD2.060alpha it gives several errors like: algorithm.d(6826): Error: template std.algorithm.swap does not match any function template declaration I think topN doesn't need to ask more features than sort() to the given range. So do you agree topN should work here? ------------------------- I think in this case topNCopy should be able to generate a truly sorted output (instead of a heap): import std.stdio, std.algorithm, std.range, std.typecons; void main() { auto a = [10, 20, 30]; auto b = ["c", "b", "a"]; Tuple!(int, string)[4] sorted_ab; writeln(a, " ", b); topNCopy!q{a > b}(zip(a, b), sorted_ab[], true); // error topNCopy!q{a > b}(zip(a, b), sorted_ab[]); // OK writeln(a, " ", b); } ------------------------- Currently I think topNCopy gives a heap instead of a sorted output when you give it a range that can't be sorted. In this the last argument of topNCopy must be false, that's the default. But if the programmer has instead given true at the last argument, can't topNCopy just sort the little result calling sort() on it before returning? This way you don't have to call sort() yourself on the result if you need it truly sorted. Do you agree on this little enhancement request? Bye, bearophile
Jun 30 2012