1 -----------------------------------------------------------------------------
2 -- |
3 -- Module : Data.Set
4 -- Copyright : (c) The University of Glasgow 2001
6 --
8 -- Stability : provisional
9 -- Portability : portable
10 --
11 -- This implementation of sets sits squarely upon Data.FiniteMap.
12 --
13 -----------------------------------------------------------------------------
15 module Data.Set (
16 Set, -- abstract, instance of: Eq
18 emptySet, -- :: Set a
19 mkSet, -- :: Ord a => [a] -> Set a
20 setToList, -- :: Set a -> [a]
21 unitSet, -- :: a -> Set a
23 union, -- :: Ord a => Set a -> Set a -> Set a
24 unionManySets, -- :: Ord a => [Set a] -> Set a
25 minusSet, -- :: Ord a => Set a -> Set a -> Set a
26 mapSet, -- :: Ord a => (b -> a) -> Set b -> Set a
27 intersect, -- :: Ord a => Set a -> Set a -> Set a
28 addToSet, -- :: Ord a => Set a -> a -> Set a
29 delFromSet, -- :: Ord a => Set a -> a -> Set a
31 elementOf, -- :: Ord a => a -> Set a -> Bool
32 isEmptySet, -- :: Set a -> Bool
34 cardinality -- :: Set a -> Int
35 ) where
37 import Prelude
39 import Data.FiniteMap
40 import Data.Maybe
42 -- This can't be a type synonym if you want to use constructor classes.
43 newtype Set a = MkSet (FiniteMap a ())
45 emptySet :: Set a
46 emptySet = MkSet emptyFM
48 unitSet :: a -> Set a
49 unitSet x = MkSet (unitFM x ())
51 setToList :: Set a -> [a]
52 setToList (MkSet set) = keysFM set
54 mkSet :: Ord a => [a] -> Set a
55 mkSet xs = MkSet (listToFM [ (x, ()) | x <- xs])
57 union :: Ord a => Set a -> Set a -> Set a
58 union (MkSet set1) (MkSet set2) = MkSet (plusFM set1 set2)
60 unionManySets :: Ord a => [Set a] -> Set a
61 unionManySets ss = foldr union emptySet ss
63 minusSet :: Ord a => Set a -> Set a -> Set a
64 minusSet (MkSet set1) (MkSet set2) = MkSet (minusFM set1 set2)
66 intersect :: Ord a => Set a -> Set a -> Set a
67 intersect (MkSet set1) (MkSet set2) = MkSet (intersectFM set1 set2)
69 addToSet :: Ord a => Set a -> a -> Set a
72 delFromSet :: Ord a => Set a -> a -> Set a
73 delFromSet (MkSet set) a = MkSet (delFromFM set a)
75 elementOf :: Ord a => a -> Set a -> Bool
76 elementOf x (MkSet set) = isJust (lookupFM set x)
78 isEmptySet :: Set a -> Bool
79 isEmptySet (MkSet set) = sizeFM set == 0
81 mapSet :: Ord a => (b -> a) -> Set b -> Set a
82 mapSet f (MkSet set) = MkSet (listToFM [ (f key, ()) | key <- keysFM set ])
84 cardinality :: Set a -> Int
85 cardinality (MkSet set) = sizeFM set
87 -- fair enough...
88 instance (Eq a) => Eq (Set a) where
89 (MkSet set_1) == (MkSet set_2) = set_1 == set_2
90 (MkSet set_1) /= (MkSet set_2) = set_1 /= set_2
92 -- but not so clear what the right thing to do is:
93 {- NO:
94 instance (Ord a) => Ord (Set a) where
95 (MkSet set_1) <= (MkSet set_2) = set_1 <= set_2
96 -}