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(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(); pool.add(new Head() .freq(a.freq+b.freq) .node(new Branch(a.node, b.node))); } } HuffmanTree get() { run(); if (nempty(pool)) tree.root(removeFirst(pool).node()); ret tree; } }