Hacker News new | past | comments | ask | show | jobs | submit login

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.



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.

[1] https://en.wikipedia.org/wiki/Schwartzian_transform




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: