Skip to content

Commit 7933406

Browse files
committed
Changed Nil to Maybe (Tree a)
1 parent db5f246 commit 7933406

File tree

1 file changed

+11
-11
lines changed
  • chapters/data_compression/huffman/code/haskell

1 file changed

+11
-11
lines changed

chapters/data_compression/huffman/code/haskell/huffman.hs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
import qualified Data.Map as M
22
import Data.List (insert, sort)
33

4-
data Tree a = Nil
5-
| Leaf Int a
4+
data Tree a = Leaf Int a
65
| Node Int (Tree a) (Tree a)
76
deriving (Show, Eq)
87

98
freq :: Tree a -> Int
10-
freq Nil = 0
119
freq (Leaf i _) = i
1210
freq (Node i _ _) = i
1311

@@ -19,10 +17,10 @@ getFrequencies = toSortedList . M.fromListWith (+) . flip zip (repeat 1)
1917
where toSortedList = sort . map swap . M.toList
2018
swap (a, i) = (i, a)
2119

22-
buildTree :: (Ord a) => [a] -> Tree a
20+
buildTree :: (Ord a) => [a] -> Maybe (Tree a)
2321
buildTree = build . map (uncurry Leaf) . getFrequencies
24-
where build [] = Nil
25-
build [t] = t
22+
where build [] = Nothing
23+
build [t] = Just t
2624
build (t1:t2:ts) = build $ insert (Node (freq t1 + freq t2) t1 t2) ts
2725

2826
data Bit = Zero | One
@@ -31,18 +29,20 @@ instance Show Bit where
3129
show Zero = "0"
3230
show One = "1"
3331

34-
encode :: (Ord a) => [a] -> (Tree a, [Bit])
32+
encode :: (Ord a) => [a] -> (Maybe (Tree a), [Bit])
3533
encode s = (tree, msg)
3634
where
3735
tree = buildTree s
3836
msg = concatMap (table M.!) s
39-
table = M.fromList $ mkTable (tree, [])
40-
mkTable (Nil, _) = []
37+
table = case tree of
38+
Nothing -> M.empty
39+
Just t -> M.fromList $ mkTable (t, [])
4140
mkTable (Leaf _ a, p) = [(a, reverse p)]
4241
mkTable (Node _ t1 t2, p) = concatMap mkTable [(t1, Zero:p), (t2, One:p)]
4342

44-
decode :: (Ord a) => Tree a -> [Bit] -> [a]
45-
decode t = path t
43+
decode :: (Ord a) => Maybe (Tree a) -> [Bit] -> [a]
44+
decode Nothing _ = []
45+
decode (Just t) m = path t m
4646
where path (Leaf _ a) m = a : path t m
4747
path (Node _ t1 _) (Zero: m) = path t1 m
4848
path (Node _ _ t2) (One: m) = path t2 m

0 commit comments

Comments
 (0)