Re:Go 1.8 Release Notes
by junke on Thursday February 16, 2017 @06:50PM
(#13664727)
But apart from reversing the resulting slice, how do you sort according to ">"? The current approach is more general and might be used with custom comparators. For example, it might be possible to implement the sort you have in mind with it.
[ Parent
| on HN ]
Re:Go 1.8 Release Notes
by justinsaccount on Thursday February 16, 2017 @07:25PM
(#13664912)
Sort could have a reverse option, but for that to work well go would need overloaded functions, or at least types that you could define an ordering on, which would let you do
a := ReverseOrder(10)
b := ReverseOrder(20)
a < b // false
sort.Slice(people, func(p Person) string { return ReverseOrder(p.Name) })
Comparison functions are just not very user friendly when what you really want to do is just sort naturally based on a list of fields. sort.Slice(people, func(p Person) (string, string, string, int) { return p.Country, P.Gender, p.Name, p.Age })
turns into a pretty messy comparison function.Not to mention, the key func aka DSU[1] approach is much faster when the comparison function is expensive to call.. imagine something like
sort.Slice(numbers, func(i, j int) bool { return num_factors(numbers[i]) < num_factors(numbers[j]) })
vs. sort.Slice(numbers, func(n int) int { return num_factors(n) })
One needs manual memoizing or caching of this function call, the other can do it internally in a much simpler manor.