简体   繁体   中英

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. 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.

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 . A case expression always matches against exactly one value, and even the first clause (which you think is working) is definitely not working.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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