fork download
  1. object Main{
  2. val freq: Int
  3. }
  4.  
  5. case class Leaf[A](element: A, freq: Int) extends Node[A]
  6. case class Branch[A](left: Node[A], right: Node[A]) extends Node[A]{
  7. val freq = left.freq + right.freq
  8. }
  9.  
  10. def huffman[A](ls: List[(A, Int)]): List[(A, String)] = {
  11. def makeTree(ls: List[Node[A]]): Node[A] = ls match{
  12. case Nil => throw new IllegalArgumentException
  13. case top :: Nil => top
  14. case _ => {
  15. val last = ls.sortBy(_.freq).slice(0, 2)
  16. makeTree(Branch(last(0), last(1)) :: ls filterNot {last.contains})
  17. }
  18. }
  19. def huffmanCode(n: Node[A], code: String): List[(A, String)] = n match{
  20. case Leaf(element, freq) => List((element, code))
  21. case Branch(left, right) => huffmanCode(left, code + "0") ::: huffmanCode(right, code + "1")
  22. case _ => throw new IllegalArgumentException
  23. }
  24. val top = makeTree(ls map {n => Leaf(n._1, n._2): Node[A]})
  25. huffmanCode(top, "")
  26. }
  27.  
  28. def main(args: Array[String]){
  29. println(huffman(List(("a", 45), ("b", 13), ("c", 12), ("d", 16), ("e", 9), ("f", 5))))
  30. }
  31. }
  32.  
Success #stdin #stdout 0.2s 211712KB
stdin
Standard input is empty
stdout
List((a,0), (c,100), (b,101), (f,1100), (e,1101), (d,111))