This turned out to be a fairly simple task and only took me a few minutes to solve. Granted, I reused some code from the logarithm calculator of a few postings ago, but that was just for the conversion of a list of numbers to their printable form.
fun binary (0, ) = "0" | (0, x) = implode ` map (fn x = if int x then chr (x + 48) else x) x | (n, b) = binary (n div 2, n mod 2 :: b) | n = binary (n, ) ;The gist of that is
- pass in a number and recurse with the number and an empty list.
- With a number that isn't zero recurse with the number divved by 2 and the list prepended with the number modded by 2.
- Keep going until the number is zero. At that point, convert the answer's digits to string representation and implode them into a single string.
- If the number is zero and there are no digits, return "0"