霍夫曼解码(在 Scala 中)

Huffman decoding (in Scala)

我正在尝试编写一种算法来执行霍夫曼解码。我是在 Scala 中做的——这是 Coursera 课程的作业,我不想违反荣誉守则,所以下面是伪代码而不是 Scala。

我编写的算法采用树 tree 和位列表 bits,并且应该 return 消息。但是,当我在提供的树上尝试时,我得到一个 NoSuchElementException (空列表的头)。我不明白为什么。

我知道我的代码可以稍微整理一下 - 我对函数式编程还是很陌生,所以我以对我有意义的方式编写它,而不是可能以最紧凑的方式编写方式。

def decode(tree, bits) [returns a list of chars]: {

    def dc(aTree, someBits, charList) [returns a list of chars]: {

        if aTree is a leaf: 

            if someBits is empty: return char(leaf) + charList
            else: dc(aTree, someBits, char(leaf) + charList)

        else aTree is a fork:

            if someBits.head is 0: dc(leftFork, someBits.tail, charList)
            else someBits is 1:  dc(rightFork, someBits.tail, charList)
        }

     dc(tree, bits, [empty list])

     }

在此先感谢您的帮助。这是我第一次使用 Whosebug,所以我可能需要学习如何最好地使用该网站。

如果我没理解错的话,你想通过叉子(根据位的指示)直到你找到一片叶子。然后您将叶值添加到您的字符列表中,并且从这一点开始您想要重复这些步骤。 如果我是对的,那么你应该将原始树传递给你的辅助方法,而不是现在是叶子的 leftForkrightFork。 所以它会是这样的:

if aTree is a leaf: 
    if someBits is empty: return char(leaf) + charList
    else: dc(tree, someBits, char(leaf) + charList)