Use generic function to compute maximum

This commit is contained in:
Holger Obermaier 2023-08-17 11:46:15 +02:00
parent ec86a83a27
commit ceff67085b

View File

@ -45,7 +45,6 @@ func sumfunc(args interface{}) (interface{}, error) {
} }
func minAnyType[T float64 | float32 | int | int32 | int64](values []T) (interface{}, error) { func minAnyType[T float64 | float32 | int | int32 | int64](values []T) (interface{}, error) {
fmt.Println(values)
if len(values) == 0 { if len(values) == 0 {
return 0.0, errors.New("min function requires at least one argument") return 0.0, errors.New("min function requires at least one argument")
} }
@ -114,19 +113,36 @@ func avgfunc(args interface{}) (interface{}, error) {
return 0.0, nil return 0.0, nil
} }
func maxAnyType[T float64 | float32 | int | int32 | int64](values []T) (interface{}, error) {
if len(values) == 0 {
return 0.0, errors.New("max function requires at least one argument")
}
var maximum T = values[0]
for _, value := range values {
if value > maximum {
maximum = value
}
}
return maximum, nil
}
// Get the maximum value // Get the maximum value
func maxfunc(args interface{}) (interface{}, error) { func maxfunc(args interface{}) (interface{}, error) {
s := 0.0 switch values := args.(type) {
values, ok := args.([]float64) case []float64:
if ok { return maxAnyType(values)
for _, x := range values { case []float32:
if x > s { return maxAnyType(values)
s = x case []int:
return maxAnyType(values)
case []int64:
return maxAnyType(values)
case []int32:
return maxAnyType(values)
default:
return 0.0, errors.New("function 'max' only on list of values (float64, float32, int, int32, int64)")
} }
} }
}
return s, nil
}
// Get the median value // Get the median value
func medianfunc(args interface{}) (interface{}, error) { func medianfunc(args interface{}) (interface{}, error) {