Open adamroyjones opened 7 months ago
Just want to note that Rust has this; https://doc.rust-lang.org/std/cmp/struct.Reverse.html .
The 'sort' package already has a Reverse function for sort.Interface, so a Reverse function for the 'cmp' package would fit well in analogy. https://pkg.go.dev/sort#Reverse
I don't think T
needs to be Ordered
. This function can reverse any comparator on two values of any
type.
https://go.dev/play/p/1TNHMQ7Cnoe
@itchyny: You're right. I'll update the proposal.
Just pondering here, should the implementation be fn(y,x)
or -fn(x,y)
? Maybe if fn
is a strict weak ordering it doesn't matter?
@randall77: It's a fair thing to ponder. I believe they're equivalent.
Let fn
be a function of type func(x, y T) int
and suppose that an asymmetric relation $<$ on $T$ can be defined as follows. (Strict weak orders are asymmetric.)
fn(x, y) > 0
, then $y < x$.fn(x, y) < 0
, then $x < y$.fn(x, y) == 0
, then neither $x < y$ nor $y < x$.The sign of fn(y, x)
is the opposite of the sign of fn(x, y)
.
fn(y, x) > 0
, then $x < y$, so fn(x, y)
cannot be positive (as it'd break the asymmetry) or zero (as $x < y$).fn(y, x) < 0
, then $y < x$, so fn(x, y)
cannot be negative (as it'd break the asymmetry) or zero (as $y < x$).fn(y, x) == 0
, then neither $x < y$ nor $y < x$, so fn(x, y)
cannot be positive or negative.I quite like the implementation that swaps the arguments as it gets quite directly to the duality, but I'm not totally wedded to it.
Proposal Details
I propose a small, trivial addition to the cmp package. (Ed.: This now incorporates an observation from @itchyny here.)
As an example,
prints out
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.