2 % (c) The AQUA Project, Glasgow University, 1994-1995
4 \section[Set]{An implementation of sets}
6 This new (94/04) implementation of sets sits squarely upon our
7 implementation of @FiniteMaps@. The interface is (roughly?) as
10 (95/08: This module is no longer part of the GHC compiler proper; it
11 is a GHC library module only, now.)
15 -- not a synonym so we can make it abstract
18 mkSet, setToList, emptySet, singletonSet,
19 union, unionManySets, minusSet,
21 intersect, isEmptySet,
24 -- to make the interface self-sufficient
25 #if defined(__GLASGOW_HASKELL__)
26 , FiniteMap -- abstract
34 import Maybes ( maybeToBool
42 -- This can't be a type synonym if you want to use constructor classes.
43 data Set a = MkSet (FiniteMap a ()) {-# STRICT #-}
46 emptySet = MkSet emptyFM
48 singletonSet :: a -> Set a
49 singletonSet x = MkSet (singletonFM 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 elementOf :: Ord a => a -> Set a -> Bool
70 elementOf x (MkSet set) = maybeToBool(lookupFM set x)
72 isEmptySet :: Set a -> Bool
73 isEmptySet (MkSet set) = sizeFM set == 0
75 mapSet :: Ord a => (b -> a) -> Set b -> Set a
76 mapSet f (MkSet set) = MkSet (listToFM [ (f key, ()) | key <- keysFM set ])
78 cardinality :: Set a -> Int
79 cardinality (MkSet set) = sizeFM set
82 instance (Eq a) => Eq (Set a) where
83 (MkSet set_1) == (MkSet set_2) = set_1 == set_2
85 -- but not so clear what the right thing to do is:
87 instance (Ord a) => Ord (Set a) where
88 (MkSet set_1) <= (MkSet set_2) = set_1 <= set_2