diff options
author | Ian Lance Taylor <iant@golang.org> | 2023-06-23 14:23:31 -0700 |
---|---|---|
committer | Gopher Robot <gobot@golang.org> | 2023-06-24 00:50:42 +0000 |
commit | ea927e560d80f34dfaaeee14418e55cc80220485 (patch) | |
tree | 1ce123d36b583c058fbb5ffebfdf87877bf6889c | |
parent | 3619255777ca544a08e1051ee641a1c1e2d0a903 (diff) | |
download | go-ea927e560d80f34dfaaeee14418e55cc80220485.tar.gz go-ea927e560d80f34dfaaeee14418e55cc80220485.zip |
slices: clarify MinFunc/MaxFunc result for equal elements
They should return the first of equal elements. No such clarification
is required for Min/Max as for them equal elements are indistinguishable.
For #60091
Change-Id: Iad58115d482add852c811e993131702b5b3bec5e
Reviewed-on: https://go-review.googlesource.com/c/go/+/505796
Run-TryBot: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Eli Bendersky <eliben@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Auto-Submit: Ian Lance Taylor <iant@google.com>
-rw-r--r-- | src/slices/sort.go | 6 | ||||
-rw-r--r-- | src/slices/sort_test.go | 28 |
2 files changed, 32 insertions, 2 deletions
diff --git a/src/slices/sort.go b/src/slices/sort.go index 24fc6e26b6..af1d51ecd4 100644 --- a/src/slices/sort.go +++ b/src/slices/sort.go @@ -70,7 +70,8 @@ func Min[S ~[]E, E cmp.Ordered](x S) E { } // MinFunc returns the minimal value in x, using cmp to compare elements. -// It panics if x is empty. +// It panics if x is empty. If there is more than one minimal element +// according to the cmp function, MinFunc returns the first one. func MinFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E { if len(x) < 1 { panic("slices.MinFunc: empty list") @@ -99,7 +100,8 @@ func Max[S ~[]E, E cmp.Ordered](x S) E { } // MaxFunc returns the maximal value in x, using cmp to compare elements. -// It panics if x is empty. +// It panics if x is empty. If there is more than one maximal element +// according to the cmp function, MaxFunc returns the first one. func MaxFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E { if len(x) < 1 { panic("slices.MaxFunc: empty list") diff --git a/src/slices/sort_test.go b/src/slices/sort_test.go index 0e9df92b63..af0585935d 100644 --- a/src/slices/sort_test.go +++ b/src/slices/sort_test.go @@ -173,6 +173,15 @@ func TestStability(t *testing.T) { } } +type S struct { + a int + b string +} + +func cmpS(s1, s2 S) int { + return cmp.Compare(s1.a, s2.a) +} + func TestMinMax(t *testing.T) { intCmp := func(a, b int) int { return a - b } @@ -214,6 +223,25 @@ func TestMinMax(t *testing.T) { } }) } + + svals := []S{ + {1, "a"}, + {2, "a"}, + {1, "b"}, + {2, "b"}, + } + + gotMin := MinFunc(svals, cmpS) + wantMin := S{1, "a"} + if gotMin != wantMin { + t.Errorf("MinFunc(%v) = %v, want %v", svals, gotMin, wantMin) + } + + gotMax := MaxFunc(svals, cmpS) + wantMax := S{2, "a"} + if gotMax != wantMax { + t.Errorf("MaxFunc(%v) = %v, want %v", svals, gotMax, wantMax) + } } func TestMinMaxNaNs(t *testing.T) { |