Arbitrary class constraints when implementing type classes in Haskell

I'm trying to implement a simple one Setin Haskell, and I'm stuck on how to express class restrictions on the elements it contains.

The type class is Setpretty simple:

class Set s where
  empty    :: s a
  isEmpty  :: s a -> Bool
  insert   :: s a -> a -> s a
  contains :: s a -> a -> Bool

A trivial implementation Setis a binary search tree:

data BinarySearchTree a = Node a (BinarySearchTree a) (BinarySearchTree a) | Leaf

I get a little stuck when it comes to declaring the correct class constraints:

  • Setit requires at least the ability to decide whether two elements are equal - its values ​​must have an instance Eq.
  • BinarySearchTreerequires its elements to have an instance Ord, since each node must have a smaller element on the left and more on the right.

, - Set, a Eq:

class Set s where
  empty    :: Eq a => s a
  isEmpty  :: Eq a => s a -> Bool
  insert   :: Eq a => s a -> a -> s a
  contains :: Eq a => s a -> a -> Bool

Set BinarySearchTree : Ord Eq, "" .

, , , BinarySearchTree , , Eq? ?

, , - BinarySearchTree, - :

data Ord a => BinarySearchTree a = Node a (BinarySearchTree a) (BinarySearchTree a) | Leaf

, : , BinarySearchTree Ord, , , , BinarySearchTree - , .

? , , ?

+4
2

Haskell: , type , . " Data.Set Functor?" , Data.Set Ord:

Data.Set.map :: Ord b => (a -> b) -> Set a -> Set b 

funct fmap

class Functor f where
  fmap :: (a -> b) -> f a -> f b

. ConstraintKinds TypeFamilies. :

class Set s where
  type SetCt s a :: Constraint
  empty    :: s a
  isEmpty  :: s a -> Bool
  insert   :: Ct a => s a -> a -> s a
  contains :: Ct a => s a -> a -> Bool

BinarySearchTree :

instance Set BinarySearchTree where
  type SetCt BinarySearchTree a = Ord a
  ...

Dominic Orchard, .

+9

-, .

Set :

class Set s where
  isEmpty  :: s a -> Bool
  insert   :: s a -> a -> s a
  contains :: s a -> a -> Bool

:

  • .
  • empty.

Set , BinarySearchTree :

{-# LANGUAGE ExistentialQuantification #-}
data BinarySearchTree a = Ord a => Node a (BinarySearchTree a) (BinarySearchTree a)
                        | Ord a => Leaf

, BinarySearchTree Ord - , BinarySearchTree a, Ord a.

, Set, empty: BinarySearchTree a, , Ord a.

, : , empty, . , .

0

All Articles