Author | Message |
---|---|
msargent
Posts: 519
|
Posted 17:31 Oct 17, 2012 |
I can't figure out what is going wrong; I keep getting a character sequence that makes no sense. Here's my code: def decode(tree: CodeTree, bits: List[Bit]): List[Char] = {
//start at top of tree and move down with each bit on the list until a leaf is reached, add a letter to the char list, repeat
//until bit list is empty
def decode0(t: CodeTree, b: List[Bit], c: List[Char]): List[Char] = t match {
case Leaf(char, weight) => if(b.isEmpty) c :+ char else decode0(tree, b.tail, c :+ char)
case Fork(left, right, chars, weight) =>
if(b.isEmpty) throw new Exception("Bit list ran out of bits before reaching a leaf")
else if (b.head == 0) decode0(left, b.tail, c)
else decode0(right, b.tail, c)
}
decode0(tree, bits, List())
}
def decodedSecret: List[Char] = decode(frenchCode, secret)
|
rabbott
Posts: 1649
|
Posted 19:03 Oct 17, 2012 |
First a simplification. else if (b.head == 0) decode0(left, b.tail, c) else decode0(right, b.tail, c)
can be changed to this.
else decode0( if (b.head == 0) left else right, b.tail, c)
The bug, though, is in the Leaf case. You are throwing away b.head without using it.
Last edited by rabbott at
19:09 Oct 17, 2012.
|
msargent
Posts: 519
|
Posted 08:12 Oct 18, 2012 |
Thanks, that worked. |