Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (*convert positive base10 number into binary number*)
- fun num2binary_aux(0,false) = "0"
- | num2binary_aux(0,true) = ""
- | num2binary_aux(n,_) = if (n mod 2) = 0 then num2binary_aux((n div 2),true)^"0"
- else num2binary_aux((n div 2),true)^"1"
- fun num2binary 0 = num2binary_aux(0,false)
- | num2binary n = num2binary_aux(n,true)
- (*convert the char into binary number which is the ascii encoding*)
- fun char2binary c = num2binary(ord(c))
- (*find the max appearance of a char in huffman tree*)
- fun maxAppearance (Symbol(x,n)) = n
- | maxAppearance (Node((_,_),Symbol(_,n),_)) = n
- | maxAppearance (Node((_,_),_,Symbol(_,n))) = n
- (*create histogram of the letter appearances*)
- fun LetterEncodingHist (Symbol(x,n)) = [(x,n)]
- | LetterEncodingHist (Node(_,T1,T2)) = (LetterEncodingHist T1)@(LetterEncodingHist T2)
- val hist = LetterEncodingHist(tree)
- (*add Zeros in the start of the list untill the length of the list is equal to the given number*)
- fun addZeros(n,lst) = if length(lst) = n then lst else #"0"::addZeros(n-1,lst)
- (*calculate the ceiling of log of the number*)
- fun log2 0 = 0 | log2 n = 1 + log2(n div 2)
- fun maxTuple [] m = m
- | maxTuple ((_,y)::xs) m = if m > y then (maxTuple xs m) else (maxTuple xs y)
- val max_app = (maxTuple hist #2(hd(hist)))
- (*save the number of bits needed to encode the number of char appearances*)
- val max_app_encode = addZeros(5,explode(num2binary(log2(max_app))))
- (*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*)
- fun encodeTuple (x,y) = addZeros(8,explode(char2binary(x))) @ (addZeros(log2(max_app),explode(num2binary(y))))
- (* add zeros at the end that the list length will be multiply of 8*)
- fun appendToCompleteMult lst = if (length(lst) mod 8) = 0 then lst else appendToCompleteMult(lst@[#"0"])
- fun reverse list = foldl op:: [] list;
- fun binary_to_num [] _ = 0
- | binary_to_num (x::xs) m = if x = #"1" then (m + (binary_to_num xs (2*m))) else (binary_to_num xs (2*m))
- fun encode_list [] temp = str(chr(binary_to_num (reverse(temp)) 1))
- | encode_list (x::xs) temp = if length(temp) = 8 then str(chr(binary_to_num (reverse(temp)) 1))^(encode_list xs [x])
- else (encode_list xs (temp@[x]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement