sclass HuffmanTreeMaker { delegate Node, Branch, Leaf to HuffmanTree. gettable new HuffmanTree tree; new TreeSet pool; int indexCounter; class Head is Comparable { int index = indexCounter++; settable Node node; settable double freq; public int compareTo(Head h) { if (this == h) ret 0; var c = cmp(freq, h.freq); if (c != 0) ret c; ret cmp(index, h.index); } } selfType importByteHistogram(int[] histogram) { int n = l(histogram); for i to n: { double freq = histogram[i]; if (freq != 0) pool.add(new Head().freq(freq).node(tree.new Leaf(i))); } this; } run { while ping (l(pool) > 1) { var it = iterator(pool); var a = it.next(); it.remove(); var b = it.next(); it.remove(); print("Merging frequencies: " + commaCombine(a.freq, b.freq)); pool.add(new Head() .freq(a.freq+b.freq) .node(tree.new Branch().zero(b.node).one(a.node))); } } HuffmanTree get() { run(); if (nempty(pool)) tree.root(popFirst(pool).node()); ret tree; } }