45e42c3a11a1fd5035fdcdcd0f08f06b4df90614
[packages/hoopl.git] / src / Compiler / Hoopl / Collections.hs
1 {- Baseclasses for Map-like and Set-like collections inspired by containers. -}
2
3 {-# LANGUAGE TypeFamilies #-}
4 #if __GLASGOW_HASKELL__ >= 701
5 {-# LANGUAGE Safe #-}
6 #endif
7
8 module Compiler.Hoopl.Collections ( IsSet(..)
9 , setInsertList, setDeleteList, setUnions
10 , IsMap(..)
11 , mapInsertList, mapDeleteList, mapUnions
12 ) where
13
14 import Data.List (foldl', foldl1')
15
16 class IsSet set where
17 type ElemOf set
18
19 setNull :: set -> Bool
20 setSize :: set -> Int
21 setMember :: ElemOf set -> set -> Bool
22
23 setEmpty :: set
24 setSingleton :: ElemOf set -> set
25 setInsert :: ElemOf set -> set -> set
26 setDelete :: ElemOf set -> set -> set
27
28 setUnion :: set -> set -> set
29 setDifference :: set -> set -> set
30 setIntersection :: set -> set -> set
31 setIsSubsetOf :: set -> set -> Bool
32
33 setFold :: (ElemOf set -> b -> b) -> b -> set -> b
34
35 setElems :: set -> [ElemOf set]
36 setFromList :: [ElemOf set] -> set
37
38 -- Helper functions for IsSet class
39 setInsertList :: IsSet set => [ElemOf set] -> set -> set
40 setInsertList keys set = foldl' (flip setInsert) set keys
41
42 setDeleteList :: IsSet set => [ElemOf set] -> set -> set
43 setDeleteList keys set = foldl' (flip setDelete) set keys
44
45 setUnions :: IsSet set => [set] -> set
46 setUnions [] = setEmpty
47 setUnions sets = foldl1' setUnion sets
48
49
50 class IsMap map where
51 type KeyOf map
52
53 mapNull :: map a -> Bool
54 mapSize :: map a -> Int
55 mapMember :: KeyOf map -> map a -> Bool
56 mapLookup :: KeyOf map -> map a -> Maybe a
57 mapFindWithDefault :: a -> KeyOf map -> map a -> a
58
59 mapEmpty :: map a
60 mapSingleton :: KeyOf map -> a -> map a
61 mapInsert :: KeyOf map -> a -> map a -> map a
62 mapDelete :: KeyOf map -> map a -> map a
63
64 mapUnion :: map a -> map a -> map a
65 mapUnionWithKey :: (KeyOf map -> a -> a -> a) -> map a -> map a -> map a
66 mapDifference :: map a -> map a -> map a
67 mapIntersection :: map a -> map a -> map a
68 mapIsSubmapOf :: Eq a => map a -> map a -> Bool
69
70 mapMap :: (a -> b) -> map a -> map b
71 mapMapWithKey :: (KeyOf map -> a -> b) -> map a -> map b
72 mapFold :: (a -> b -> b) -> b -> map a -> b
73 mapFoldWithKey :: (KeyOf map -> a -> b -> b) -> b -> map a -> b
74
75 mapElems :: map a -> [a]
76 mapKeys :: map a -> [KeyOf map]
77 mapToList :: map a -> [(KeyOf map, a)]
78 mapFromList :: [(KeyOf map, a)] -> map a
79
80 -- Helper functions for IsMap class
81 mapInsertList :: IsMap map => [(KeyOf map, a)] -> map a -> map a
82 mapInsertList assocs map = foldl' (flip (uncurry mapInsert)) map assocs
83
84 mapDeleteList :: IsMap map => [KeyOf map] -> map a -> map a
85 mapDeleteList keys map = foldl' (flip mapDelete) map keys
86
87 mapUnions :: IsMap map => [map a] -> map a
88 mapUnions [] = mapEmpty
89 mapUnions maps = foldl1' mapUnion maps