简体   繁体   English

Haskell:case语句中的Parse错误(涉及列表!)

[英]Haskell: Parse error in case statement (involving lists!)

I'm having trouble with (I assume) the types I am working with (for an assignment on huffman coding) in my case statement. 在我的case语句中,我遇到了(我假设)我正在使用的类型(对于霍夫曼编码的赋值)。 I want to work from the top of the tree down to each leaf and return a list of key value pairs. 我想从树的顶部到每个叶子工作,并返回一个键值对列表。 [ ] passes fine, but [h] returns a parse error and I'm not sure why. []传递正常,但[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))]

Also I haven't used bangs before but I think they are appropriate here? 我之前没有用过刘海,但我觉得它们在这里合适吗? Would they have an impact on performance? 它们会对性能产生影响吗? Am I even using them in the right context? 我是否在正确的背景下使用它们?

case ab of ... does not match against both a and b , but rather matches on the result of calling a as a function, with the argument b . case ab of ...ab都不匹配,而是匹配调用a作为函数的结果,参数为b A case expression always matches against exactly one value, and even the first clause (which you think is working) is definitely not working. case表达式总是与一个值匹配,甚至第一个子句(您认为有效)也绝对不起作用。

To match against two values, you wrap them up in a tuple, and then break apart the tuple in each clause, like so: 要匹配两个值,将它们包装在一个元组中,然后在每个子句中拆分元组,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM