scala编码做霍夫曼解码,但结果错误

scala coding to do the Huffman decoding, but wrong result

 abstract class CodeTree
  case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
  case class Leaf(char: Char, weight: Int) extends CodeTree


type Bit = Int
 def decode(tree: CodeTree, bits: List[Bit]): List[Char] = {
 if(!bits.isEmpty) {
     bits.head match {

  case 0 => tree match {
    case Fork(l, r, _, _) => decode(l, bits.tail)
    case Leaf(_, _) =>  chars(tree) ::: decode(frenchCode, bits.tail)

  }
  case 1 => tree match {
    case Fork(l, r, _, _) => decode(r, bits.tail)
    case Leaf(_, _) =>  chars(tree) ::: decode(frenchCode, bits.tail)

  }
}
}
else Nil
 }

  val frenchCode: CodeTree = Fork(Fork(Fork(Leaf('s',121895),Fork(Leaf('d',56269),Fork(Fork(Fork(Leaf('x',5928),Leaf('j',8351),List('x','j'),14279),Leaf('f',16351),List('x','j','f'),30630),Fork(Fork(Fork(Fork(Leaf('z',2093),Fork(Leaf('k',745),Leaf('w',1747),List('k','w'),2492),List('z','k','w'),4585),Leaf('y',4725),List('z','k','w','y'),9310),Leaf('h',11298),List('z','k','w','y','h'),20608),Leaf('q',20889),List('z','k','w','y','h','q'),41497),List('x','j','f','z','k','w','y','h','q'),72127),List('d','x','j','f','z','k','w','y','h','q'),128396),List('s','d','x','j','f','z','k','w','y','h','q'),250291),Fork(Fork(Leaf('o',82762),Leaf('l',83668),List('o','l'),166430),Fork(Fork(Leaf('m',45521),Leaf('p',46335),List('m','p'),91856),Leaf('u',96785),List('m','p','u'),188641),List('o','l','m','p','u'),355071),List('s','d','x','j','f','z','k','w','y','h','q','o','l','m','p','u'),605362),Fork(Fork(Fork(Leaf('r',100500),Fork(Leaf('c',50003),Fork(Leaf('v',24975),Fork(Leaf('g',13288),Leaf('b',13822),List('g','b'),27110),List('v','g','b'),52085),List('c','v','g','b'),102088),List('r','c','v','g','b'),202588),Fork(Leaf('n',108812),Leaf('t',111103),List('n','t'),219915),List('r','c','v','g','b','n','t'),422503),Fork(Leaf('e',225947),Fork(Leaf('i',115465),Leaf('a',117110),List('i','a'),232575),List('e','i','a'),458522),List('r','c','v','g','b','n','t','e','i','a'),881025),List('s','d','x','j','f','z','k','w','y','h','q','o','l','m','p','u','r','c','v','g','b','n','t','e','i','a'),1486387)
  val secret: List[Bit] = List(0,0,1,1,1,0,1,0,1,1,1,0,0,1,1,0,1,0,0,1,1,0,1,0,1,1,0,0,1,1,1,1,1,0,1,0,1,1,0,0,0,0,1,0,1,1,1,0,0,1,0,0,1,0,0,0,1,0,0,0,1,0,1)
  def decodedSecret: List[Char] = decode(frenchCode, secret)ode here

我是scala新手,正在学习模式匹配,想做huffman解码,现在可以得到一个列表,但是是错误的答案,希望有人能指出错误。

您的代码存在几个问题。

  1. 打叶子不想吃一点。如果您的代码中没有位,则还应添加叶子的字符。

  2. 在解码方法中,您不想引用 frenchCode,而是作为参数给出的代码。

  3. 您可以通过模式匹配访问叶子的字符,即 case Leaf(codeChar, _) => ...

顺便说一句。如果您开始在树上进行匹配,您的代码将更加清晰。只有当它与叉子匹配时,您才会查看位列表的头部。

希望对您有所帮助。 ;)