| 1 |
// compile |
| 2 |
|
| 3 |
// Copyright 2022 The Go Authors. All rights reserved. |
| 4 |
// Use of this source code is governed by a BSD-style |
| 5 |
// license that can be found in the LICENSE file. |
| 6 |
|
| 7 |
package main |
| 8 |
|
| 9 |
import "fmt" |
| 10 |
|
| 11 |
type IntLike interface { |
| 12 |
~int | ~int64 | ~int32 | ~int16 | ~int8 |
| 13 |
} |
| 14 |
|
| 15 |
func Reduce[T any, U any, Uslice ~[]U](function func(T, U) T, sequence Uslice, initial T) T { |
| 16 |
result := initial |
| 17 |
for _, x := range sequence { |
| 18 |
result = function(result, x) |
| 19 |
} |
| 20 |
return result |
| 21 |
} |
| 22 |
|
| 23 |
func min[T IntLike](x, y T) T { |
| 24 |
if x < y { |
| 25 |
return x |
| 26 |
} |
| 27 |
return y |
| 28 |
} |
| 29 |
|
| 30 |
// Min returns the minimum element of `nums`. |
| 31 |
func Min[T IntLike, NumSlice ~[]T](nums NumSlice) T { |
| 32 |
if len(nums) == 0 { |
| 33 |
return T(0) |
| 34 |
} |
| 35 |
return Reduce(min[T], nums, nums[0]) |
| 36 |
} |
| 37 |
|
| 38 |
// VarMin is the variadic version of Min. |
| 39 |
func VarMin[T IntLike](nums ...T) T { |
| 40 |
return Min(nums) |
| 41 |
} |
| 42 |
|
| 43 |
type myInt int |
| 44 |
|
| 45 |
func main() { |
| 46 |
fmt.Println(VarMin(myInt(1), myInt(2))) |
| 47 |
|
| 48 |
seq := []myInt{1, 2} |
| 49 |
fmt.Println(Min(seq)) |
| 50 |
fmt.Println(VarMin(seq...)) |
| 51 |
} |