Advertisement
Guest User

Untitled

a guest
Jun 2nd, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (*convert positive base10 number into binary number*)
  2.     fun num2binary_aux(0,false) = "0"
  3.     | num2binary_aux(0,true) = ""
  4.     | num2binary_aux(n,_) = if (n mod 2) = 0 then num2binary_aux((n div 2),true)^"0"
  5.         else num2binary_aux((n div 2),true)^"1"        
  6.     fun num2binary 0 = num2binary_aux(0,false)
  7.         | num2binary n = num2binary_aux(n,true)
  8.     (*convert the char into binary number which is the ascii encoding*)
  9.     fun char2binary c = num2binary(ord(c))
  10.     (*find the max appearance of a char in huffman tree*)
  11.     fun maxAppearance (Symbol(x,n)) = n
  12.         | maxAppearance (Node((_,_),Symbol(_,n),_)) = n
  13.         | maxAppearance (Node((_,_),_,Symbol(_,n))) = n
  14.     (*create histogram of the letter appearances*)
  15.     fun LetterEncodingHist (Symbol(x,n)) = [(x,n)]
  16.     | LetterEncodingHist (Node(_,T1,T2)) = (LetterEncodingHist T1)@(LetterEncodingHist T2)
  17.     val hist = LetterEncodingHist(tree)
  18.     (*add Zeros in the start of the list untill the length of the list is equal to the given number*)
  19.     fun addZeros(n,lst) = if length(lst) = n then lst else #"0"::addZeros(n-1,lst)
  20.     (*calculate the ceiling of log of the number*)
  21.     fun log2 0 = 0 | log2 n = 1 + log2(n div 2)  
  22.     fun maxTuple [] m = m
  23.         | maxTuple ((_,y)::xs) m = if m > y then (maxTuple xs m) else (maxTuple xs y)
  24.     val max_app = (maxTuple hist #2(hd(hist)))
  25.     (*save the number of bits needed to encode the number of char appearances*)
  26.     val max_app_encode = addZeros(5,explode(num2binary(log2(max_app))))
  27.     (*encode the first var of the Tuple to it binary which represent the ascii of the char and the appearance of the char to binary*)
  28.     fun encodeTuple (x,y) = addZeros(8,explode(char2binary(x))) @ (addZeros(log2(max_app),explode(num2binary(y))))
  29.     (* add zeros at the end that the list length will be multiply of 8*)
  30.     fun appendToCompleteMult lst = if (length(lst) mod 8) = 0 then lst else appendToCompleteMult(lst@[#"0"])    
  31.     fun reverse list = foldl op:: [] list;
  32.     fun binary_to_num [] _ = 0
  33.         | binary_to_num (x::xs) m = if x = #"1" then (m + (binary_to_num xs (2*m))) else (binary_to_num xs (2*m))
  34.     fun encode_list [] temp = str(chr(binary_to_num (reverse(temp)) 1))
  35.         | encode_list (x::xs) temp = if length(temp) = 8 then str(chr(binary_to_num (reverse(temp)) 1))^(encode_list xs [x])
  36.                                    else (encode_list xs (temp@[x]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement