Tuesday, October 06, 2015

[mLite] Convert to Binary Notation

A short diversion: the Standard ML dialect called mLite is where I go for the intellectual challenge of thinking in a functional programming way. Kudos to Nils M. Holm for developing it. mLite is one of the languages I use to solve RosettaCode tasks, in this case, Binary Digits.

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"
Might get back to some VB6 next. Or javascript.