Skip to content

Commit ea927e5

Browse files
ianlancetaylorgopherbot
authored andcommitted
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 golang#60091 Change-Id: Iad58115d482add852c811e993131702b5b3bec5e Reviewed-on: https://go-review.googlesource.com/c/go/+/505796 Run-TryBot: Ian Lance Taylor <[email protected]> Reviewed-by: Eli Bendersky <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Auto-Submit: Ian Lance Taylor <[email protected]>
1 parent 3619255 commit ea927e5

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/slices/sort.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,8 @@ func Min[S ~[]E, E cmp.Ordered](x S) E {
7070
}
7171

7272
// MinFunc returns the minimal value in x, using cmp to compare elements.
73-
// It panics if x is empty.
73+
// It panics if x is empty. If there is more than one minimal element
74+
// according to the cmp function, MinFunc returns the first one.
7475
func MinFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E {
7576
if len(x) < 1 {
7677
panic("slices.MinFunc: empty list")
@@ -99,7 +100,8 @@ func Max[S ~[]E, E cmp.Ordered](x S) E {
99100
}
100101

101102
// MaxFunc returns the maximal value in x, using cmp to compare elements.
102-
// It panics if x is empty.
103+
// It panics if x is empty. If there is more than one maximal element
104+
// according to the cmp function, MaxFunc returns the first one.
103105
func MaxFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E {
104106
if len(x) < 1 {
105107
panic("slices.MaxFunc: empty list")

src/slices/sort_test.go

+28
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,15 @@ func TestStability(t *testing.T) {
173173
}
174174
}
175175

176+
type S struct {
177+
a int
178+
b string
179+
}
180+
181+
func cmpS(s1, s2 S) int {
182+
return cmp.Compare(s1.a, s2.a)
183+
}
184+
176185
func TestMinMax(t *testing.T) {
177186
intCmp := func(a, b int) int { return a - b }
178187

@@ -214,6 +223,25 @@ func TestMinMax(t *testing.T) {
214223
}
215224
})
216225
}
226+
227+
svals := []S{
228+
{1, "a"},
229+
{2, "a"},
230+
{1, "b"},
231+
{2, "b"},
232+
}
233+
234+
gotMin := MinFunc(svals, cmpS)
235+
wantMin := S{1, "a"}
236+
if gotMin != wantMin {
237+
t.Errorf("MinFunc(%v) = %v, want %v", svals, gotMin, wantMin)
238+
}
239+
240+
gotMax := MaxFunc(svals, cmpS)
241+
wantMax := S{2, "a"}
242+
if gotMax != wantMax {
243+
t.Errorf("MaxFunc(%v) = %v, want %v", svals, gotMax, wantMax)
244+
}
217245
}
218246

219247
func TestMinMaxNaNs(t *testing.T) {

0 commit comments

Comments
 (0)