Guest User

Untitled

a guest
Jan 21st, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 0.88 KB | None | 0 0
  1. -module(huffman).
  2. -export([print_codewords/1]).
  3.  
  4. print_codewords(Text) ->
  5.     Tree = mk_tree(freq_dict(Text)),
  6.     Codewords = codewords(Tree),
  7.     lists:foreach(fun({Chr, Code}) -> io:fwrite("~c: ~w~n", [Chr, Code]) end, Codewords).
  8.  
  9. codewords({L, R}) ->
  10.     codewords(L, <<0:1>>) ++ codewords(R, <<1:1>>).
  11.  
  12. codewords({L, R}, <<Bits/bits>>) ->
  13.     codewords(L, <<Bits/bits, 0:1>>) ++ codewords(R, <<Bits/bits, 1:1>>);
  14. codewords(Symbol, <<Bits/bitstring>>) ->
  15.     [{Symbol, Bits}].
  16.  
  17. mk_tree([{Tmp, _}]) -> Tmp;
  18. mk_tree(Tmp) ->
  19.     [{A1, B1}, {A2, B2} | Rest] = lists:keysort(2, Tmp),
  20.     mk_tree([{{A1, A2}, B1+B2} | Rest]).
  21.  
  22. freq_dict(Text) ->
  23.     freq_dict(lists:sort(Text), []).
  24.  
  25. freq_dict([], Acc) -> Acc;
  26. freq_dict([Chr | Rest], Acc) ->
  27.     {ChrBlock, OtherChrs} = lists:splitwith(fun(X) -> X == Chr end, Rest),
  28.     freq_dict(OtherChrs, [{Chr, 1+length(ChrBlock)} | Acc]).
Add Comment
Please, Sign In to add comment