(* An example of the caml language *) (* Convert an integer to a string describing that integer *) (* This exception is just in case something goes wrong. Don't worry though, nothing will go wrong. *) exception Illegal_num (* This is a trinary, three individual digits *) type trinary = int * int * int (* Convert a single ones digit to a string *) let ones_to_string = function | 0 -> "" | 1 -> " one" | 2 -> " two" | 3 -> " three" | 4 -> " four" | 5 -> " five" | 6 -> " six" | 7 -> " seven" | 8 -> " eight" | 9 -> " nine" | _ -> raise Illegal_num (* Convert a single tens digit to a string *) let tens_to_string = function | 0 -> "" | 2 -> " twenty" | 3 -> " thirty" | 4 -> " fourty" | 5 -> " fifty" | 6 -> " sixty" | 7 -> " seventy" | 8 -> " eighty" | 9 -> " ninety" | _ -> raise Illegal_num (* Convert teens to string *) let teens_to_string = function | 0 -> " ten" | 1 -> " eleven" | 2 -> " twelve" | 3 -> " thirteen" | 4 -> " fourteen" | 5 -> " fifteen" | 6 -> " sixteen" | 7 -> " seventeen" | 8 -> " eighteen" | 9 -> " nineteen" | _ -> raise Illegal_num (* Convert three digits to hundreds, tens, ones string *) let trinary_to_string (a,b,c) = (if a > 0 then (ones_to_string a) ^ " hundred" else "") ^ (if b = 1 then (teens_to_string c) else (tens_to_string b) ^ (ones_to_string c)) (* Remove three digits from the right side, return them and the new number *) let remove_triad n = let a = (n mod 1000) / 100 in let b = (n mod 100) / 10 in let c = n mod 10 in ((n / 1000),(a,b,c)) (* Recursively build the string *) let rec iter_triads n postfix = if n > 0 then let (new_num,tri) = remove_triad n in (iter_triads new_num (List.tl postfix)) ^ (trinary_to_string tri) ^ (List.hd postfix) else "" (* Main function, given an int convert to a string *) let int_to_string n = let postfixes = [""; " thousand"; " million"; " billion"] in if n = 0 then "zero" else let str = iter_triads n postfixes in if (String.length str) > 1 then (String.sub str 1 ((String.length str) - 1)) else "" (* Program entry point. Test on a list of integers *) let _ = let nums = [0;1;13;123;5434;1234567891234;57;1066123001] in let strs = List.map int_to_string nums in List.iter (fun s -> print_string s ; print_newline()) strs