【发布时间】:2017-07-12 09:57:34
【问题描述】:
我正在尝试编写一种算法来执行霍夫曼解码。我在 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])
}
提前感谢您的帮助。这是我第一次使用 StackOverflow,所以我可能需要学习如何最好地使用该网站。
【问题讨论】:
标签: algorithm scala huffman-code