Using different order for sets

I read Chapter 2 of Purely Functional Data Structures, which talks about unordered sets implemented as binary search trees. The code is written in ML and ends with signature ORDEREDand functor UnbalancedSet(Element: ORDERED): SET. Based on more C ++ background, this makes sense to me; custom objects of the comparison function are part of the type and can be passed at build time, and this seems to be pretty similar to the way the ML functor works.

When it comes to Haskell, it seems that the behavior depends only on the instance Ord, so if I wanted to have a set whose order was canceled, it looks like I would have to use an instance newtype, for example

newtype ReverseInt = ReverseInt Int deriving (Eq, Show)

instance Ord ReverseInt where
    compare (ReverseInt a) (ReverseInt b)  
        | a == b = EQ
        | a < b  = GT
        | a > b  = LT

which I could use in a set:

let x = Set.fromList $ map ReverseInt [1..5]

, newtype Ord?

+4
1

, . , newtype , :

  • Set a a, , ( , , ). , Set a.
  • coerce . , xs = [1,2,3] :: Int ys = [ReverseInt 1, ReverseInt 2, ReverseInt 3] :: [ReverseInt] ys = coerce xs :: [ReverseInt]. , Set ( - , , , ).
  • newtype , . , ReverseInt , Ord: Down. , Down Int ReversedInt, , !

, , Set, , , . -

data Set a = Set { comparisionKey :: a -> a -> Ordering
                 , ...
                 }

, , Set, .

+9

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


All Articles