| 1 |
// Copyright 2021 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package a |
| 6 |
|
| 7 |
type Numeric interface { |
| 8 |
~int | ~int8 | ~int16 | ~int32 | ~int64 | |
| 9 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | |
| 10 |
~float32 | ~float64 | |
| 11 |
~complex64 | ~complex128 |
| 12 |
} |
| 13 |
|
| 14 |
// numericAbs matches numeric types with an Abs method. |
| 15 |
type numericAbs[T any] interface { |
| 16 |
Numeric |
| 17 |
Abs() T |
| 18 |
} |
| 19 |
|
| 20 |
// AbsDifference computes the absolute value of the difference of |
| 21 |
// a and b, where the absolute value is determined by the Abs method. |
| 22 |
func absDifference[T numericAbs[T]](a, b T) T { |
| 23 |
d := a - b |
| 24 |
return d.Abs() |
| 25 |
} |
| 26 |
|
| 27 |
// orderedNumeric matches numeric types that support the < operator. |
| 28 |
type orderedNumeric interface { |
| 29 |
~int | ~int8 | ~int16 | ~int32 | ~int64 | |
| 30 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | |
| 31 |
~float32 | ~float64 |
| 32 |
} |
| 33 |
|
| 34 |
// Complex matches the two complex types, which do not have a < operator. |
| 35 |
type Complex interface { |
| 36 |
~complex64 | ~complex128 |
| 37 |
} |
| 38 |
|
| 39 |
// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639). |
| 40 |
// // orderedAbs is a helper type that defines an Abs method for |
| 41 |
// // ordered numeric types. |
| 42 |
// type orderedAbs[T orderedNumeric] T |
| 43 |
// |
| 44 |
// func (a orderedAbs[T]) Abs() orderedAbs[T] { |
| 45 |
// if a < 0 { |
| 46 |
// return -a |
| 47 |
// } |
| 48 |
// return a |
| 49 |
// } |
| 50 |
// |
| 51 |
// // complexAbs is a helper type that defines an Abs method for |
| 52 |
// // complex types. |
| 53 |
// type complexAbs[T Complex] T |
| 54 |
// |
| 55 |
// func (a complexAbs[T]) Abs() complexAbs[T] { |
| 56 |
// r := float64(real(a)) |
| 57 |
// i := float64(imag(a)) |
| 58 |
// d := math.Sqrt(r*r + i*i) |
| 59 |
// return complexAbs[T](complex(d, 0)) |
| 60 |
// } |
| 61 |
// |
| 62 |
// // OrderedAbsDifference returns the absolute value of the difference |
| 63 |
// // between a and b, where a and b are of an ordered type. |
| 64 |
// func OrderedAbsDifference[T orderedNumeric](a, b T) T { |
| 65 |
// return T(absDifference(orderedAbs[T](a), orderedAbs[T](b))) |
| 66 |
// } |
| 67 |
// |
| 68 |
// // ComplexAbsDifference returns the absolute value of the difference |
| 69 |
// // between a and b, where a and b are of a complex type. |
| 70 |
// func ComplexAbsDifference[T Complex](a, b T) T { |
| 71 |
// return T(absDifference(complexAbs[T](a), complexAbs[T](b))) |
| 72 |
// } |