list - Haskell : Parse error in case statement (involving lists!)

标签 list parsing haskell compiler-errors tree

我在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)) -> ...
  ...

关于list - Haskell : Parse error in case statement (involving lists!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43752251/

相关文章:

Python __init__ setattr 关于参数?

json - Delphi - 在运行时解析 JSON 数据时发生访问冲突

inheritance - Haskell 中的可插拔 AI

haskell - 为什么 <$> 慢?

Python:在文本文件中搜索字符串并显示匹配的行

java - 理解 list[i-1] 与 list[i]-1

list - 为什么这些列表在 Erlang 中不等价?

ios - 来自 NSInputStream 的 UIImage

java - 将数据导入 mongodb 时出现 JSONParseException

http - 使用 Warp 的惰性字节串流