A set of an unordered data type with a given order

I am trying to put this data type in a Haskell dataset, but I do not want to give it a generic instance of Ord. Therefore, I want to give a set of orders for y-coördinate, but without an instance of Ord Vector. Is it possible?

    data Vector = V 
    { x :: Double
    , y :: Double
    } deriving (Eq)
+3
source share
3 answers

SetYou must use the Orddefault instance for the item type.

If you want to use another instance Ord, the standard way to do this is to use a special wrapper newtypeand then write an instance Ordfor this:

newtype Y = Y { unY :: Vector } deriving Eq
instance Ord Y where compare = comparing ((y . unY) &&& (x . unY))

But since this comparison method is equivalent to how binary tuples are compared, KennyTM is the simplest solution here.

+8

:

toTuple :: Vector -> (Double, Double)
toTuple (V x y) = (y, x)

fromTuple :: (Double, Double) -> Vector
fromTuple (y, x) = V x y

Ord ( ), Set. ( - .)

+4

I created a version of a type Setthat has no context Ord, but instead requires a type function a -> a -> Orderingpassed in where it is being built Set. Could this be useful in your case?

(I'm not sure about the status of copyrights, it is largely untested and the documentation has not been changed, so I’m not just putting it here ...)

0
source

Source: https://habr.com/ru/post/1738450/


All Articles