2

I'm trying to learn Haskell. I am trying to implement a Huffman Tree. The parameters of my decode function are (basically, the 'signature'):

decode :: HTree -> [Int] -> [Char]

So, given the tree, and a list of numbers, I want to return the decoded message. Suppose a = 01, b = 1, c = 001, d = 000.

I know how to do it when I can use two trees for decoding. i.e:

decode :: HTree -> HTree -> [Int] -> [Char]

Concisely put, keep the first tree as the original tree, and make the other tree go left or right based on the next number in [Int] (if it's 0, go left, if it's 1, go right). Repeat this until a leaf is reached, and then add the leaf into the list of [Char] and continue using recursion. However, I am trying to do this with just one tree, i.e:

decode :: HTree -> [Int] -> [Char]

but I can't see how to store the original HTree as I traverse through it looking for a leaf. I there a way to do this in haskell?

1 Answers1

2

Just write a recursive helper function that has access to the original tree:

decode :: HTree -> [Int] -> [Char]
decode orig = go orig
  where go :: HTree -> [Int] -> [Char]
        go curr = -- use both orig and curr here
amalloy
  • 89,153
  • 8
  • 140
  • 205
  • I just realized that as you posted the comment. This should do the trick. Thanks. (will accept the answer soon) – user2272600 Feb 12 '20 at 00:58
  • 1
    both this answer and the one in the linked entry fail to mention explicitly that the "helper function" is defined in the nested scope of the original `decode` function. a non-nested (top-level) `decode_helper :: HTree -> HTree -> [Int] -> [Char]` would also have access to the original (this is the Prolog way to achieve this, since it doesn't have nested scope). in Haskell/LC-based languages/ turning a nested function into the top-level one by adding parameters to it is known as "lambda lifting". – Will Ness Feb 13 '20 at 07:53