我在case语句中遇到了(我假设)正在使用的类型(用于霍夫曼编码的分配)的麻烦。我想从树的顶部一直到每个叶子,并返回键值对的列表。 []正常,但[h]返回解析错误,我不确定为什么。

type HCode = [Bit]
data Bit = L | R deriving (Eq, Show)
data Tree a = Leaf Int a | Node Int (Tree a) (Tree a) deriving (Eq)

convert :: Ord a => HCode -> Tree a -> [(a,HCode)]
convert hs tree =
  case hs tree of
    []     (Node _ a b) -> (convert [L]            a)++(convert [R]            b)
    [h]    (Node _ a b) -> (convert !([h]++[L])    a)++(convert !([h]++[R])    b)
    (h:hs) (Node _ a b) -> (convert !((h:hs)++[L]) a)++(convert !((h:hs)++[R]) b)
    [h]    (Leaf _ a)   -> [(a, [h])]
    (h:hs) (Leaf _ a)   -> [(a, (h:hs))]

我以前也没用过刘海,但我觉得这里合适吗?它们会对性能产生影响吗?我什至在正确的环境中使用它们吗?

最佳答案

case a b of ...不能同时匹配ab,而是匹配使用参数a调用b作为函数的结果。 case表达式始终与一个值完全匹配,甚至第一个子句(您认为有效)也绝对不起作用。

要与两个值匹配,可以将它们包装在一个元组中,然后在每个子句中将其拆分,如下所示:

case (hs, tree) of
  ([], (Node _ a b)) -> ...
  ([h], (Node _ a b)) -> ...
  ...

10-06 10:16
查看更多