lo
lo copied to clipboard
comparison function in MinBy and MaxBy seems inconsistent
func MinBy[T any](collection []T, comparison func(T, T) bool) T {
var min T
if len(collection) == 0 {
return min
}
min = collection[0]
for i := 1; i < len(collection); i++ {
item := collection[i]
if comparison(item, min) {
min = item
}
}
return min
}
func MaxBy[T any](collection []T, comparison func(T, T) bool) T {
var max T
if len(collection) == 0 {
return max
}
max = collection[0]
for i := 1; i < len(collection); i++ {
item := collection[i]
if comparison(item, max) {
max = item
}
}
return max
}
comparison in MinBy is less,while in MaxBy is greater. In most of the generics library, just need one comparison function, less, such as C++ STL. This minimizes user misuse.
https://en.cppreference.com/w/cpp/algorithm/ranges/max
Why do MinBy and MaxBy are exists? Both are exactly same without name, and there is no logic for decide which one is Max or Min.