lo icon indicating copy to clipboard operation
lo copied to clipboard

comparison function in MinBy and MaxBy seems inconsistent

Open rbee3u opened this issue 2 years ago • 2 comments

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.

rbee3u avatar May 06 '22 02:05 rbee3u

https://en.cppreference.com/w/cpp/algorithm/ranges/max

rbee3u avatar May 06 '22 02:05 rbee3u

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.

wirekang avatar May 06 '22 12:05 wirekang