2

This is my Huffman coding that returns an empty list. My purpose was to make it add all the pairs to listenr1 but it seams to only return an empty list. I'm not sure why it's not appending, but I think I have misunderstood a fundamental part of Scheme programming. I do not want to use append*. I think the appending might be wrong, but I'm not exactly sure why. Is there a way to replace listenr1 each time it appends maybe?

(define (huffman-leafs tree)
  (let ((listenr1 '()))
    (define (iterator currentbranch)
      (let ((left (left-branch currentbranch))
            (right (right-branch currentbranch)))
        (if (leaf? left)
            (list (symbols left) (weight left))
            (append listenr1 (iterator left)))
        (if (leaf? right)
            (list (symbols right) (weight right))
            (append listenr1 (iterator right)))))
    (iterator tree)
    listenr1))

(huffman-leafs mytree)
Will Ness
  • 70,110
  • 9
  • 98
  • 181

1 Answers1

0

The code you've written looks like a good start, but it's mixing recursive and non-recursive idioms.

The huffman tree is (I assume) either a LEAF? in which case it has SYMBOLS and WEIGHT. Otherwise it's got LEFT-BRANCH and RIGHT-BRANCH.

So we can define a single recursive function to list all the leaves like this:

(define (huffman-leafs tree)
  (if (leaf? tree)
      ;;; list this leaf alone
      ;;; else, use recursion (huffman-leafs (left-branch tree)) and right branch
      ;; and APPEND those together
      ))

Hope that helps!

river
  • 1,028
  • 6
  • 16