简体   繁体   中英

Haskell: negate a value of type Ordering

Is there a way to negate or invert a value of type Ordering? Something like this:

inv = not compare

If you are getting the Ordering from compare , then you can change it to flip compare :

> flip compare 3 4
GT

Or you can wrap the values in Down from Data.Ord , a newtype that exists to reverse the ordering of things:

> compare (Down 3) (Down 4)
GT

If you can't or don't want to change the place that the Ordering comes from, you'll need a function to invert it and I don't know of a built-in one. You can write the obvious pattern match, or since Ordering is itself ordered:

inv :: Ordering -> Ordering
inv = compare EQ

Yes it is contained in Data.Ord and is a type called Down .

I cite:

"If a has an Ord instance associated with it then comparing two values thus wrapped will give you the opposite of their normal sort order."

Reference: https://hackage.haskell.org/package/base-4.10.1.0/docs/Data-Ord.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM