【问题标题】:Non exhaustive pattern error when decoding Huffman tree?解码霍夫曼树时出现非详尽模式错误?
【发布时间】:2020-02-22 07:50:11
【问题描述】:

我正在尝试将 Huffman 树和位流转换为字符列表以及指示输出是否消耗所有输入位的布尔值。这是一个例子:

decode xyz_code [True,False,True,True,True,False,False,True] = 
("yzyx",False)

这是我目前所拥有的,但它不起作用。怎么了?救命!

data BTree a = Leaf a | Fork (BTree a) (BTree a) deriving (Show, Eq)

decode :: BTree a -> [Bool] -> ([a], Bool)
decode _ [] = ([],True)
decode (Leaf v) [bs] = ([v], bs)
decode (Fork left right) (b:bs)
   | b         = decode right bs
   | otherwise = decode left bs

【问题讨论】:

  • 编译器认为decode (Leaf v) [bs] 不包含长度≥ 2 的列表。
  • 我该如何解决?
  • 一般来说,如果它不应该发生,要么将其定义为错误,要么重新排列你的类型,使其永远不存在。
  • 你能说得更具体点吗?我不明白出了什么问题,我应该改变什么

标签: haskell recursion functional-programming huffman-code


【解决方案1】:
  • _ [] 覆盖空列表
  • (Fork left right) (b:bs) 包含 Forks 的非空列表
  • (Leaf v) [bs] 涵盖 Leafs 的长度为 1 的列表

那么编译器警告您的遗漏是什么? Leafs 的长度 > 1 的列表。您需要将这种情况定义为某种东西。如果达到该状态在逻辑上无效,则可以出错:

data BTree a = Leaf a | Fork (BTree a) (BTree a) deriving (Show, Eq)

decode :: BTree a -> [Bool] -> ([a], Bool)
decode _ [] = ([], True)
decode (Leaf v) [bs] = ([v], bs)
decode (Leaf v) _ = error "Too much code left at leaf"
decode (Fork left right) (b:bs)
   | b         = decode right bs
   | otherwise = decode left bs

【讨论】:

    【解决方案2】:

    标题似乎表明您收到有关模式匹配不完整的警告。考虑一下:

    58567334.hs:6:1: warning: [-Wincomplete-patterns]
        Pattern match(es) are non-exhaustive
        In an equation for `decode': Patterns not matched: (Leaf _) (_:_:_)
      |
    6 | decode _ [] = ([],True)
      | ^^^^^^^^^^^^^^^^^^^^^^^^...
    

    它表示不包括涉及任何 Leaf 且布尔值列表长于两个的模式。

    [] 上匹配的第一个模式匹配空列表。

    [bs] 匹配的下一个模式与一个名为bs 的具有单个元素 的列表匹配。这是一个常见的错误。

    您可能想要这种模式:

    decode (Leaf v) bs = -- ...
    

    其中bs[Bool] 值(即布尔值列表)。

    现在您必须弄清楚如何将该布尔值列表聚合到单个 Bool

    【讨论】:

      猜你喜欢
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多