Open
Description
Proposal Details
I propose a small, trivial addition to the cmp package. (Ed.: This now incorporates an observation from @itchyny here.)
// Reverse takes a comparison function and returns the reverse of it.
func Reverse[T any](fn func(x, y T) int) func(x, y T) int {
return func(x, y T) int { return fn(y, x) }
}
As an example,
package main
import (
"cmp"
"fmt"
"slices"
)
func main() {
fn := func(x, y int) int { return cmp.Compare(x, y) }
xs := []int{2, 3, 1}
fmt.Printf("%v\n", xs)
slices.SortFunc(xs, fn)
fmt.Printf("%v\n", xs)
slices.SortFunc(xs, Reverse(fn))
fmt.Printf("%v\n", xs)
}
func Reverse[T any](fn func(x, y T) int) func(x, y T) int {
return func(x, y T) int { return fn(y, x) }
}
prints out
[2 3 1]
[1 2 3]
[3 2 1]
I've found that it's frequently useful to want to assert that something is ordered ascending or descending; writing such a thing down is trivial but feels rather clumsy.
I'm happy to contribute a pull request with tests if this is considered a good idea.
Metadata
Metadata
Assignees
Type
Projects
Status
Incoming