Initial commit
This commit is contained in:
42
sortable.go
Normal file
42
sortable.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package stl
|
||||
|
||||
// ImplicitSortable are types that can be compared with
|
||||
// the less operator <, among others.
|
||||
//
|
||||
// As with C++, two keys are considered equal if neither
|
||||
// x < y nor y < x, so these interfaces have nothing to
|
||||
// do with Go's 'comparable' whatsoever.
|
||||
//
|
||||
// This behavior can be overridden by defining another
|
||||
// type and then add a Compare method to the original key.
|
||||
type ImplicitSortable interface {
|
||||
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~string | ~float32 | ~float64
|
||||
}
|
||||
|
||||
// Sorter is a interface used in the construction of
|
||||
// many collection types, to compare two keys with
|
||||
// the '<' operator by default.
|
||||
type Sorter[T any] interface {
|
||||
Compare(x, y T) bool
|
||||
}
|
||||
|
||||
// Less implements Sorter for ImplicitSortables using the '<' operator.
|
||||
type Less[T ImplicitSortable] struct{}
|
||||
|
||||
func (Less[T]) Compare(x, y T) bool {
|
||||
return x < y
|
||||
}
|
||||
|
||||
// Greater implements Sorter for ImplicitSortables using the '>' operator.
|
||||
type Greater[T ImplicitSortable] struct{}
|
||||
|
||||
func (Greater[T]) Compare(x, y T) bool {
|
||||
return x > y
|
||||
}
|
||||
|
||||
// Equal determines if the two keys are considered equal,
|
||||
// i.e., neither x < y nor y < x, per C++ traditions.
|
||||
func Equal[C Sorter[T], T any](x, y T) bool {
|
||||
var c C
|
||||
return !c.Compare(x, y) && !c.Compare(y, x)
|
||||
}
|
Reference in New Issue
Block a user