霍夫曼解码(在Scala中)

gad*_*dje 5 algorithm scala huffman-code

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

我编写的算法采用树tree和位列表bits,并且应该返回消息.但是,当我在提供的树上尝试它时,我得到一个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])

     }
Run Code Online (Sandbox Code Playgroud)

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

Rum*_*mid 4

如果我理解正确的话,你想要穿过叉子(从位的方向)直到找到一片叶子。然后,您将叶值添加到字符列表中,从此时起您要重复步骤。如果我是对的,那么你应该将原始树传递给你的辅助方法,而不是 aleftForkrightFork,它们现在是叶子。所以它会是这样的:

if aTree is a leaf: 
    if someBits is empty: return char(leaf) + charList
    else: dc(tree, someBits, char(leaf) + charList)
Run Code Online (Sandbox Code Playgroud)