Browse Source

Code for 07 mar.

Abhinav Sarkar 4 years ago
parent
commit
55ec9bacb2
1 changed files with 55 additions and 0 deletions
  1. 55
    0
      2016-03-07/TreeMap.hs

+ 55
- 0
2016-03-07/TreeMap.hs View File

@@ -0,0 +1,55 @@
1
+module TreeMap where
2
+
3
+import Data.List (foldl, nub, sort)
4
+import Data.Maybe (fromMaybe)
5
+
6
+data TreeMap k v = EmptyNode | Node k v (TreeMap k v) (TreeMap k v) deriving (Show)
7
+
8
+insert :: Ord k => TreeMap k v -> (k, v) -> TreeMap k v
9
+insert EmptyNode (k, v) = Node k v EmptyNode EmptyNode
10
+insert (Node nk nv l r) i@(k, v)
11
+  | k == nk = Node k v l r
12
+  | k <  nk = Node nk nv (insert l i) r
13
+  | k >  nk = Node nk nv l (insert r i)
14
+
15
+get :: Ord k => TreeMap k v -> k -> Maybe v
16
+get EmptyNode _ = Nothing
17
+get (Node nk nv l r) k
18
+  | k == nk = Just nv
19
+  | k <  nk = get l k
20
+  | k >  nk = get r k
21
+
22
+keys :: TreeMap k v -> [k]
23
+keys EmptyNode = []
24
+keys (Node nk nv l r) = keys l ++ [nk] ++ keys r
25
+
26
+values :: TreeMap k v -> [v]
27
+values EmptyNode = []
28
+values (Node nk nv l r) = values l ++ [nv] ++ values r
29
+
30
+toList :: TreeMap k v -> [(k, v)]
31
+toList EmptyNode = []
32
+toList (Node k v l r) = toList l ++ [(k, v)] ++ toList r
33
+
34
+fromList :: Ord k => [(k, v)] -> TreeMap k v
35
+fromList = foldl insert EmptyNode
36
+
37
+prop_keysAreUnique :: Ord k => [(k, v)] -> Bool
38
+prop_keysAreUnique l = (length . nub . keys $ t) == (length . keys $ t) where t = fromList l
39
+
40
+prop_nonMemberGetIsNothing :: (Ord k, Eq v) => [(k, v)] -> k -> Bool
41
+prop_nonMemberGetIsNothing l notk = (get t notk) == Nothing where t = fromList [(k, v) | (k, v) <- l, k /= notk]
42
+
43
+prop_duplicateInsertGetsLastValue :: (Ord k, Eq v) => [(k, v)] -> k -> v -> v -> Bool
44
+prop_duplicateInsertGetsLastValue l k v1 v2 = get (insert (insert t (k, v1)) (k, v2)) k == Just v2 where t = fromList l
45
+
46
+prop_toListIsInorder :: (Ord k, Eq v) => [(k, v)] -> Bool
47
+prop_toListIsInorder l = (map fst . toList . fromList) l ==  (nub . sort . map fst) l
48
+
49
+prop_insertDoesNotRemoveKeys :: (Ord k) => [(k, v)] -> (k, v) -> Bool
50
+prop_insertDoesNotRemoveKeys l i =
51
+  lbefore == lafter || lbefore + 1 == lafter
52
+  where
53
+    lbefore = length . toList t
54
+    lafter = length . toList (insert t i)
55
+    t = fromList l

Loading…
Cancel
Save