on 5cc025d help sign in
project-m36/RelationTuple.hs
70 lines 2.8 kB history raw
1module RelationTuple where
2import RelationType
3import RelationAttribute
4import qualified Data.Map as M
5import qualified Data.Set as S
6import qualified Data.List as L
7import qualified Data.HashSet as HS
9tupleSize :: RelationTuple -> Int
10tupleSize (RelationTuple m) = M.size m
12tupleAttributeNameSet :: RelationTuple -> S.Set AttributeName
13tupleAttributeNameSet (RelationTuple tupMap) = M.keysSet tupMap
15tupleAtomForAttribute :: RelationTuple -> AttributeName -> Atom
16tupleAtomForAttribute (RelationTuple tupMap) attrName = tupMap M.! attrName
18{-instance Show RelationTuple where
19 show (RelationTuple t) = show $ M.toAscList t-}
21--in case the oldattr does not exist in the tuple, then return the old tuple
22tupleRenameAttribute :: AttributeName -> AttributeName -> RelationTuple -> RelationTuple
23tupleRenameAttribute oldattr newattr old@(RelationTuple tmap) =
24 if M.notMember oldattr tmap
25 then old
26 else
27 RelationTuple newmap
28 where
29 newmap = M.insert newattr oldvalue deletedKeyMap
30 oldvalue = tmap M.! oldattr
31 deletedKeyMap = M.delete oldattr tmap
33--in case the map does not contain the attributes, filter them out
34mkRelationTuple :: S.Set AttributeName-> M.Map AttributeName Atom -> RelationTuple
35mkRelationTuple attrs map = RelationTuple newMap
36 where
37 --make sure only attributes in the name set are in the tuple
38 --check that Atoms are all of the same type- change to Either return value
39 newMap = remapWithAttributes attrs map
41mkRelationTuples :: Attributes -> [M.Map AttributeName Atom] -> [RelationTuple]
42mkRelationTuples attrs maplist = map mapper maplist
43 where
44 mapper m = RelationTuple $ remapWithAttributes (attributeNameSet attrs) m
46singleTupleSetJoin :: RelationTuple -> RelationTupleSet -> RelationTupleSet
47singleTupleSetJoin tup tupSet = HS.foldr tupleJoiner HS.empty tupSet
48 where
49 tupleJoiner tuple2 accumulator = case joinedTuple of
50 Nothing -> accumulator
51 Just relTuple -> HS.insert relTuple accumulator
52 where joinedTuple = singleTupleJoin tup tuple2
54singleTupleJoin :: RelationTuple -> RelationTuple -> Maybe RelationTuple
55singleTupleJoin (RelationTuple tup1) (RelationTuple tup2) = newTuple
56 where
57 newTuple = if M.isSubmapOfBy (==) matchingMap tup2 then
58 Just $ RelationTuple (M.union tup1 tup2)
59 else
60 Nothing
61 matchingMap = M.intersection tup1 tup2
64tupleExtend :: RelationTuple -> RelationTuple -> RelationTuple
65tupleExtend (RelationTuple map1) (RelationTuple map2) = RelationTuple $ M.union map1 map2
67{- sort the associative list to match the header sorting -}
68tupleSortedAssocs :: RelationTuple -> [(AttributeName, Atom)]
69tupleSortedAssocs (RelationTuple tupMap) = L.sortBy (\x y -> compare (fst x) (fst y)) (M.assocs tupMap)